您好,欢迎光临本网站![请登录][注册会员]  
文件名称: Netty4.1实战-手写RPC框架.pdf
  所属分类: Java
  开发工具:
  文件大小: 780kb
  下载次数: 0
  上传时间: 2019-09-01
  提 供 者: yao__s*******
 详细说明:RPC是一种远程调用的通信协议,例如dubbo、thrift等,我们在互联网高并发应用开发时候都会使用到类似的服务。本专题主要通过三个章节实现一个rpc通信的基础功能,来学习RPC服务中间件是如何开发和使用。章节内以源码加说明实战方式来讲解,请尽可能下载源码学习。 - 手写RPC框架第一章《自定义配置xml》 - 手写RPC框架第二章《netty通信》 - 手写RPC框架第三章《RPC中间件》2019/9/1 Markdoc preview MET八-INF spring schemas test HelloserviceImpl. java resource itstack-rpc-provider. xml Provider config java public class Provider Config private String nozzle;//接口 private String ref;/映射 private String alia5;//别名 //发布 protected void doExport() I System. out. format("生产者信息=>[接∏:%s][映射:%s][别名:%s]n\n", nozzle,ref,a1as); public String getNozzle()[ return nozzle public void setNozzle(String nozzle)t this, nozzle nozzle public String getRef()i return ref public void setRef(String ref)f this ref refi lblic String getAlias()( return alias; public void setAlias(String alias)i this, alias ali Provider Bean. java public class Provider Bean extends Provider Config implements ApplicationcontextAware i OVerride public void setApplicationContext(Applicationcontext applicationcontext) throws BeansExceptior 发布生产者 My Bean Definition Parser java public class My BeanDefinitionParser implements BeanDefinition Parser i 3/25 2019/9/1 Markdoc preview private final Class beanclass My BeanDefinitionParser(Class beanclass )t this beanclass beancli public Bean Definition parse(Elementelement, ParserContext parser Context)t RootBeanDefinition beanDefinition= new RootBeanDefinition i beanDefinition. set BeanClass(beanClass): beanDefinition. setLazyInit(false)i String be element getAttribute("id"); parsercontext. getRegistry().registerBeanDefinition(beanName, beanDefinition); for (Method method beanclass. getMethods())f if (lisProperty (method, beanClass)) continue String name method getName (); String methodName name substring(3, 4). toLower Case+ name substring(4); String value element getAttribute(methodName); beanDefinition. getPropertyvalues(. addProperty Value( methodName, value )i return beanE finition private boolean isproperty(Method method, Class beanclass)i String methodName = method. getName() boolean flag methodName, length>3&& methodName startswith( set")&& Modifier, isPublic(method. getModifiers())&& method. getParameterTypes().length ==1 Method getter null; if (! flag) return false Class type method get Parameter Types ([0] ry getter beanClass getMethod ("get"+ methodName substring(3)); y catch(NoSuchMethodException ignore)i if (null = getter)( try I getter= beanclass getMethod("is"+ methodName substring(3)) t catch (NoSuchMethodException ignore )I flag getter != null & Modifier.isPublic(getter, getModifiers())&& type equals(getter. getReturnType(); return flag public class My Name spaceHandler extends Names paceHandlerSupport t public void inito t registerBeanDefinitionParser("consumer", new My BeanDefinitionParser(Consumer Bean class)); register BeanDefinitionParser("provider", new My BeanDefinitionParser(ProviderBean class)); register BeanDefinition Parser("server", new My BeanDefinitionParser(ServerBean. class)) pc xsd 4/25 2019/9/1 Markdoc preview org.itstack demo rpc config. ServerConfig--> d: el d plexcontent> beans: identified xsd: attribute name=host" type="xsd: string"> Xsd: documentation> /xsd: ai xsd: documentation tati XSd: documentation> xsd: documentation><[ CDATA[服务别名分组信息] xsd: documentation><[ CDATA[接口名称1]/xsd: documentation f type= xsd: string Xsd: documentation> cxsd: al xsd: documentation> beansxmlns=http://www.springframework.org/schema/beans xmlns:xsi-http://nww.w3.oRg/2001/xmlsChema-instancexmlns:rpc=http://rpc.itstack.org/schema/rpc si:schemalocation=http://www.spriNgframework.org/schema/beanshttp://www.springframeworkorg/schema/beans/spring beans. xsd http://rpc.itstark.org/schema/rpchttp://rpc.itstack.org/schema/rpc/rpc.xsd"> itstack-rpc-provider. xml kage org. itstack demo test import org. springframework context support. ClassPathXmlApplicationContext g w create by fuzhengwei on 201975/4 本本章节主要介绍如何读取自定义配置xm文件字没信息 public class ApiTest i public static void main(String[ args)i Stringl configs =i"itstack-rpc-consumer xml","itstack-rpc-provider xmI"; new ClassPathXmlApplicationContext(configs) 测试结果 2019-05-07 19: 44: 24, 805 main INFo [org. springframework context support. ClassPathXmlApplicationcontext: prepareRefresh: 510] Refreshing org. spring framework. context support. ClassPathXmlApplicationContext299a06ac: startup date [Tue May 07 19: 44: 24CST 2019]: root of context hierarchy 2019-05-07 19: 44: 24, 872 main INFo [org. springframework. beans. factory. xml. XmlBeanDefinitionReader: load BeanDefinitions: 315] Loading XML bean definitions from class path resource [itstack-rpc-consumer xml 2019-05-07 19: 44: 24,972 main INFo [ org. springframework beans. factory. xml. XmIBeanDefinition Reader: load BeanDefinitions: 315] Loading XML bean definitions from class path resource [itstack-rpc-provider xm1 2819-65-6719:44:25,608 main IN}o Corg. spring framework. beans. factory support. DefaultListableBeanFactory: preInstantiateSingletons: 5771-Pre-instantiating 2019/9/1 Markdoc preview singletons in org. spring framework, beans. factory support. DefaultListableBean Factory192b07fd: defining beans consumer itstack, consumer helloservice, provider helloservice]; root of factory hierarchy 服务端信息=>[注册中心地址:127.8.8,1][注册中心端口:637 生产老信息->[接口:org. attack.dero.test, service, Hello5 ervice】[映射:he1 sErvice][别名: itstackRpc] 第二章、net通信 案例介绍在我们实现rp框架的时候,需要选择soke的通信方式。而我们知道一般情况下 socke通信类似与qq聊天,发过去消息,什么时候回复都可以。但是我们rpc 框架通信,从感觉上类似htt调用,需要在一定时间内返回,否则就会发生超时断开 这里我们选择net作为我们的 socke架,采用 future方式进行通信。 Nety是由BOSS提供的 开源框架。Ne提供异步的、事件驱动的网络应用程序框架和工具,用以快速开发高性能、高可靠性的网络服务器和客户端 程序。也就是说,Ney是一个基于No的客户、服务器端编程框架,使用Nety可以确俣你快速和简单的开发出一个网络应用,例如实现了某科协议的客户 服务端应用。Nety相当于简化和流线化了网络应用的编程开发过程,例如:基于TCP和UDP的 socket服务开发。“快速"和简单并不用产生维护性或性能上的 问题。Ne:y是一个吸收了多科协议(包括FTP、SMTP、HTTP等各种二进制文本协议)的实现经验,并经过相当精心设计的项目。最终,Nety成功的找到了 种方式,在保证易于开发的同时还保证了其应用的性能,稳定性和伸缩性。 环境准备1、jdk1.802、 IntelliJ IDEA Community Edition2018.3.1×64 代码示例 itstack-demo-rpc-02 ma org. itstack. demo. rpc network client C⊥ ientsocket,java My. Handler. java RprDecoder. java RPcEncoder. java future Syncwrite. java SyncWriteFuture. java SyncwriteMap. j Writef ms server H-MyServerHandler.java Serversocket. java til SerializationUtil J test org. itstack. demo test Startclient. java Client Socket. java package org. itst ack demo rpc network client; import io netty bootstrapBootstrap; import io netty channel. ChannelFuture import io netty channel. ChannelInitializer import io netty channel.Cha import io netty channel. EventLoop Group; import io netty channel nio. NioEventLoopGroup import io netty. ch tet. Socketch annel y channel socket nio. NioSocketch 1 import org. itstack demo rpc network codec. RpcDecoder import org. itstack twork codec. rpcencoder import org. itstack rpc, network. msg Request; import org. itstack demo rpc network. msg Response; * http://www.itstack 7125 2019/9/1 Markdoc preview s create by fuzhengwei on 2019/5/6 public class clientsocket implements Runnable private ChannelFuture future public void runt EventLoopGroup workerGroup new NiaEventLoopGroupo; ry i Bootstrap b= new Bootstrap); b group(w b channel(NioSocketChannel. class) boption( Channeloption AUTO READ, true) b handler(new ChannelInitializer< Socket channel>of override public void initchannel( SocketChannel ch) throws Exception h pipeline(). ad pcDecoder( Response, class) Encoder(Request new MyClientHandler() ChannelFuture f= b connect( 127.0.0.1", 7397) sync() f channel(. closeFuture(). sync() uptedException e)t e printstackTrace( an worker Group. shut downGracefullyo blic Channelfuture (){ return future public void setFuture( Channel Future future )i this, future fu My ClientHandler java package org. itstack demo rpc network client; import io netty channel Channe lHandlercontext; import io netty channel Channe lInboundHandlerAdapteri import org. itstack demo rpc network. future. SyncWriteFuture; import org.itstack, demo rpc network. future. SyncwriteMap import org. itstack demo rpc network. msg Response; http://www.itstack.org s create by fuzhengwei on 2019/576 public class MyClientHandler extends ChannelInboundHandlerAdapter ao public void channelRead( ChannelHandler Context ctx, object obj) throws Exception i Response msg =(Response) obj: String requestId msg getRequestIdo; SynchriteFuture future =(SyncWriteFuture)SyncwriteMap syncKey get(requestId) if (future != null)i uture setResponse( msg); } Override public void exception Caught( ChannelHandlerContext ctx, Throwable cause)I causeprintstackTrace() ctx. close 2019/9/1 Markdoc preview er ava package org. itstack demo rpc network codec; import io netty buffer. ByteBuf import io netty channel Channe lHandlercontext; import io netty handler codec. ByteToMes sageDecoder: import org. itstack demo rpc network util. SerializationUtil; http://wvw.itstack.org x create by fuzhengwei on 2019/5/6 public class RpcDecoder extends Byte ToMessageDecoder i private Class genericclass public RpcDecoder(Class(?> genericclass)( this. genericClass genericclass protected void decode( channelHandlerContext ctx, ByteBuf in List out)t if (in. readableByteso)< 4)i int dataLength =in. readInt(; o< dataLength)[ n. resetReaderIndex(: byte[] dat a new byte [dataLength]; in readBytes(data) out. add( SerializationUtil deserialize( data, genericclass)); RI package org. itstack demo rpc network codec; import io netty buffer. ByteBuf import io netty channel Channe lHandlercontext; ort i dler codec Mes sageToByteEn coder; import org. itstack demo rpc. net work. util. Serializat ionutil *http://www.itstack.org create by fuzhengwei on 2019/5/6 public class RpcEncoder extends Message ToByte Encoder i private Class genericclass public RpcEncoder(Class genericclass)[ this genericclass genericclass oVerride protected void encode(ChannelHandlerContext ctx, object in, ByteBuf out )i if(genericclass,isInstance(in))( byte[] data SerializationUtil serialize(in); out.writeInt(data length)i out write Bytes(data) 2019/9/1 Markdoc preview SyncWrite package org.itstack demo rpc network. future import io netty channel. Channel mport io netty channel. ChannelFuture import io netty channel. ChannelFutureListener import org. itstack demo rpc. net work. msg. Request mport org.itstack, demo rpc network. msg. Response import java.util. UUID import java. util. concurrent TimeUnit; import java. util. concurrent. TimeoutException; public class Syncwrite i ublic Response writeAndSync(final Channel channel, final Request request, final long timeout) throws Exception f if (channel = null)t throw new NullPointerException("channel"); if (request = null)t throw new NullPointerException ("request" ); if (timeout <= 0) throw new IllegalArgumentException( timeout <-0"); String requestId UUID randomUUIDO. tostring() request. setRequestId(requestId) WriteFuture future new SyncWriteFuture (request. getRequestIdo)); SyncWriteMap. syncKey put(request. getRequestIdo, future); Response response- dowriteAndSync(channel, request, timeout, future); SyncwriteMap. syncKey remove(request. getRequestId(); return response private Response dowriteAndSync(final Channel channel, final Request request, final long timeo WriteFuture< Response> write Future)throws Exception i channel. writeAnd Flush (request). addListener(new ChannelFuturelisteneroi public void operation Camplete( Channe l Future future)throws Exception i write Future. setwriteResult(future. isSuccess() write Future set Cause( future cause()); /失败移蜍 if (lwriteFuture iswriteSuccess())I SyncWriteMap. syncKey remove(writeFuture requestIdO); Response response write Future. get(timeout, TimeUnit MILLISECONDS)i if (response = null) i if (write Future. isTimeouto) else i //write exception throw new Exception(writeFuture cause()); SyncWrite Future jav package org. itstack demo rpc network. future: mport org.itstack demo rpc network. msg. Response
(系统自动生成,下载前可以参看下载内容)

下载文件列表

相关说明

  • 本站资源为会员上传分享交流与学习,如有侵犯您的权益,请联系我们删除.
  • 本站是交换下载平台,提供交流渠道,下载内容来自于网络,除下载问题外,其它问题请自行百度
  • 本站已设置防盗链,请勿用迅雷、QQ旋风等多线程下载软件下载资源,下载后用WinRAR最新版进行解压.
  • 如果您发现内容无法下载,请稍后再次尝试;或者到消费记录里找到下载记录反馈给我们.
  • 下载后发现下载的内容跟说明不相乎,请到消费记录里找到下载记录反馈给我们,经确认后退回积分.
  • 如下载前有疑问,可以通过点击"提供者"的名字,查看对方的联系方式,联系对方咨询.
 相关搜索: netty4核心原理pdf
 输入关键字,在本站1000多万海量源码库中尽情搜索: