05-基础增强-第5天(轻量级RPC框架开发)-讲义_第1页
05-基础增强-第5天(轻量级RPC框架开发)-讲义_第2页
05-基础增强-第5天(轻量级RPC框架开发)-讲义_第3页
05-基础增强-第5天(轻量级RPC框架开发)-讲义_第4页
05-基础增强-第5天(轻量级RPC框架开发)-讲义_第5页
已阅读5页,还剩24页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1.RPC原理学习RPC(RemoteProcedureCallProtocol)——远程过程调用协议,它是一种通过网络从远RPC开发包括网络分布式多程序在内的应用程序更加容易。RPC采用客户机/服务器模式。请求程序就是一个客户机,而服务提供程序就是一个服息。在服务器端,进程保持睡眠状态直到调用信息到达为止。当一个调用信息到达,服务器1.2.RPC原理运行时,一次客户机对服务器的RPC调用,其内部操作大致有如下十步:1.调用客户端句柄;执行传送参数2.调用本地系统内核发送网络消息3.消息传送到远程主机4.服务器句柄得到消息并取得参数5.执行远程过程6.执行的过程将结果返回服务器句柄7.服务器句柄返回结果,调用远程系统内核8.消息传回本地主机9.客户句柄由内核接收消息10.客户接收句柄返回的数据1.3.hadoopRPC演示2.nio原理学习2.1.简介有的原始类型提供(Buffer)缓存支持。字符集编码解码解决方案。Channel:一个新的原始见代码2.3.socketnio原理使用传统的I/O程序读取文件内容,并写入到另一个文件(或Socket),如下程序:File.read(fileDesc,buf,len);Socket.send(socket,buf,len);会有较大的性能开销,主要表现在一下两方面:1.上下文切换(contextswitch),此处有4次用户态和内核态的切换其运行示意图如下1)先将文件内容从磁盘中拷贝到操作系统buffer4)从socketbuffer拷贝到协议引擎.2.3.2.NIONIO技术省去了将操作系统的readbuffer拷贝到程序的buffer,以及从程序buffer拷贝到socketbuffer的步骤,直接将readbuffer拷贝到socketbuffer.java的FileChannel.transferTo()方法就是这样的实现,这个实现是依赖于操作系统底层的sendFile()实现的.publicvoidtransferTo(longposition,longcount,WritableByteChanneltarget);他的底层调用的是系统调用sendFile()方法sendfile(intout_fd,intin_fd,off_t*offset,size_tcount);如下图3.1.netty简介Netty是基于JavaNIO的网络应用框架.例如服务器和客户端协议。Netty提供了一种新的方式来使开发网络应用程序,这种新的方和有很强的扩展性。Netty的内部实现时很复杂的,但是Netty提供了api。Netty是完全基于NIO实现的,所以整个tty网络应用程序通常需要有较高的可扩展性,无论是Netty还是其他的基于JavaNIO的框架,都会提供可扩展性的解决方案。Netty中一个关键组成部分是它的异步特性.下载netty包3.2.2.服务端启动类packagety.demo.server;importty.bootstrap.ServerBootstrap;importty.channel.Channel;importty.channel.ChannelFuture;importty.channel.ChannelInitializer;importty.channel.EventLoopGroup;importty.channel.nio.NioEventLoopGroup;importty.channel.socket.nio.NioServerSocketChannel;/**一个请求连接或接收数据时该做什么**@authorwilson*publicclassEchoServer{privatefinalintport;publicEchoServer(intport){this.port=port;}publicvoidstart()throwsException{EventLoopGroupeventLoopGroup=null;try{//创建ServerBootstrap实例来引导绑定和启动服务器ServerBootstrapserverBootstrap=newServerBootstrap();//创建NioEventLoopGroup对象来处理事件,如接受新连接、接收数据、写数据等等eventLoopGroup=newNioEventLoopGroup();某个端口已等待客户端连接。serverBootstrap.group(eventLoopGroup).channel(NioServerSocketChannel.class).localAddress("localhost",port).childHandler(newChannelInitializer<Channel>(){//设置childHandler执行所有的连接请求@OverrideprotectedvoidinitChannel(Channelch)throwsException{ch.pipeline().addLast(newEchoServerHandler());}cChannelFuturechannelFuture=serverBootstrap.bind().sync();System.out.println("开始监听,端口为:"+channelFuture.channel().localAddress());channelFuture.channel().closeFuture().sync();}finally{eventLoopGroup.shutdownGracefully().sync();}}publicstaticvoidmain(String[]args)throwsException{newEchoServer(20000).start();}}3.2.3.服务端回调方法packagety.demo.server;importty.channel.ChannelFutureListener;importty.channel.ChannelHandlerContext;importty.channel.ChannelInboundHandlerAdapter;importjava.util.Date;publicclassEchoServerHandlerextendsChannelInboundHandlerAdapter{@OverridepublicvoidchannelRead(ChannelHandlerContextctx,Objectmsg)throwsException{SystemSystem.out.println("server读取数据……");//读取数据ByteBufbuf=(ByteBuf)msg;byte[]req=newbyte[buf.readableBytes()];Stringbody=newString(req,"UTF-8");System.out.println("接收客户端数据:"+body);//向客户端写数据System.out.println("server向client发送数据");StringcurrentTime=newDate(System.currentTimeMillis()).toString();ByteBufresp=Unpooled.copiedBuffer(currentTime.getBytes());iteresp}@OverridepublicvoidchannelReadComplete(ChannelHandlerContextctx)throwsException{System.out.println("server读取数据完毕..");ctxflush刷新后才将数据发出到SocketChannel}@OverridepublicvoidexceptionCaught(ChannelHandlerContextctx,Throwablecause)throwsException{causeprintStackTrace();ctx.close();}}3.2.4.客户端启动类packagepackagecomnettydemoclient;ty.bootstrap.Bootstrap;importty.channel.ChannelFuture;importty.channel.ChannelInitializer;importty.channel.EventLoopGroup;importty.channel.nio.NioEventLoopGroup;importty.channel.socket.SocketChannel;importty.channel.socket.nio.NioSocketChannel;import.InetSocketAddress;/***•连接服务器•写数据到服务器•等待接受服务器返回相同的数据•关闭连接**@authorwilson*publicclassEchoClient{privatefinalStringhost;privatefinalintport;publicEchoClient(Stringhost,intport){this.host=host;this.port=port;}publicvoidstart()throwsException{EventLoopGroupnioEventLoopGroup=null;try{//创建Bootstrap对象用来引导启动客户端Bootstrapbootstrap=newBootstrap();up为是一个线程池,这个线程池用来处理连接、接受数据、发送数据nioEventLoopGroup=newNioEventLoopGroup();地址bootstrap.group(nioEventLoopGroup).channel(NioSocketChannel.class).remoteAddress(newInetSocketAddress(host,port)).handler(newChannelInitializer<SocketChannel>(){//添加一个ChannelHandler,客户端成功连接服务器后就会被执行@OverrideprotectedvoidinitChannel(SocketChannelch)throwsException{ch.pipeline().addLast(newEchoClientHandler());}//•调用Bootstrap.connect()来连接服务器ChannelFuturef=bootstrap.connect().sync();//•最后关闭EventLoopGroup来释放资源f.channel().closeFuture().sync();}finally{nioEventLoopGroup.shutdownGracefully().sync();}}}publicstaticvoidmain(String[]args)throwsException{newEchoClient("localhost",20000).start();}}3.2.5.客户端回调方法packagecomnettydemoclient;rByteBufUtilimportty.channel.ChannelHandlerContext;importty.channel.SimpleChannelInboundHandler;publicclassEchoClientHandlerextendsSimpleChannelInboundHandler<ByteBuf>{//客户端连接服务器后被调用@OverridepublicvoidchannelActive(ChannelHandlerContextctx)throwsException{System.out.println("客户端连接服务器,开始发送数据……");byte[]req="QUERYTIMEORDER".getBytes();ByteBuffirstMessage=Unpooled.buffer(req.length);firstMessage.writeBytes(req);ctx.writeAndFlush(firstMessage);}//•从服务器接收到数据后调用@OverrideprotectedvoidchannelRead0(ChannelHandlerContextctx,ByteBufmsg)throwsException{System.out.println("client读取server数据..");//服务端返回消息后ByteBufbuf=(ByteBuf)msg;byte[]req=newbyte[buf.readableBytes()];Stringbody=newString(req,"UTF-8");System.out.println("服务端数据为:"+body);}//•发生异常时被调用@OverridepublicvoidexceptionCaught(ChannelHandlerContextctx,Throwablecause)throws见代码ExceptionException{System.out.println("clientexceptionCaught..");//释放资源ctx.close();}}3.3.1.简介Handler可以完成通讯报文的解码编码、拦截指定的报文、统一对日志错误进行处理、统一对请求进行计数、控制Handler执行与否。一句话,没有它做不到的只有你想不到的。Netty中的所有handler都实现自ChannelHandler接口。按照输出输出来分,分为nelInboundHandlerChannelOutboundHandlerChannelInboundHandler户端发往服务器的报文进行处理,一般用来执行解码、读取客户端数据、进行业务处理等;Netty中,可以注册多个handler。ChannelInboundHandler按照注册的先后顺序执行;3.3.2.代码3.3.3.总结1、ChannelInboundHandler之间的传递,通过调用ctx.fireChannelRead(msg)实现;调用ctx.write(msg)将传递到ChannelOutboundHandler。2、ctx.write()方法执行后,需要调用flush()方法才能令它立即执行。3、ChannelOutboundHandler在注册的时候需要放在最后一个ChannelInboundHandler之前,法传递到ChannelOutboundHandler。Handler后一个处理。3.4.netty发送对象3.4.1.简介Netty中,通讯的双方建立连接后,会把数据按照ByteBuf的方式进行传输,例如http协议3.4.2.代码见代码4.spring注解学习4.1.spring的初始化顺序4.1.1.通过ApplicationContextAware加载Spring上下文环境4.1.2.InitializingBean的作用4.1.3.如果使用注解@Component4.1.4.结论setApplicationContext()方法进行操作t()方法执行完毕后,调用afterPropertiesSet()方法进行操作4.2.注解使用回顾l册<context:component-scanbase-package=”pagkage1[,pagkage2,…,pagkageN]”/>。的头上带有特定的注解@Component/@Repository/@Service/@Controller,ng3、在使用spring管理的bean时,无需在对调用的对象进行new的过程,只需使用@Autowired将需要的bean注入本类即可4.3.1.解释1、自定义注解的作用:在反射中获取注解,以取得注解修饰的“类、方法、属性”的相关@Target表示该注解用于什么地方,可能的ElemenetType参数包括:ElemenetType.CONSTRUCTOR构造器声明ElemenetType.FIELD域声明(包括enum实例)ElemenetType.LOCAL_VARIABLE局部变量声明ElemenetType.METHOD方法声明ElemenetType.PACKAGE包声明ElemenetType.PARAMETER参数声明ElemenetType.TYPE类,接口(包括注解类型)或enum声明@Retention表示在什么级别保存该注解信息。可选的RetentionPolicy参数包括:RetentionPolicy.SOURCE注解将被编译器丢弃RetentionPolicyCLASSclass会被VM丢弃RetentionPolicy.RUNTIMEJVM将在运行期也保留注释,因此可以通过反射机4.3.2.实现定义自定义注解@@Target({ElementType.TYPE})//注解用在接口上@Retention(RetentionPolicy.RUNTIME)//VM将在运行期也保留注释,因此可以通过反射机制读取注解的信息@Componentpublic@interfaceRpcService{Stringvalue();}2、将直接类加到需要使用的类上,我们可以通过获取注解,来得到这个类@@RpcService("HelloService")publicclassHelloServiceImplimplementsHelloService{publicStringhello(Stringname){return"Hello!"+name;}}publicpublicinterfaceHelloService{Stringhello(Stringname);}4、通过ApplicationContext获取所有标记这个注解的类@@ComponentpublicclassMyServerimplementsApplicationContextAware{@SuppressWarnings("resource")publicstaticvoidmain(String[]args){newClassPathXmlApplicationContext("spring2.xml");}publicvoidsetApplicationContext(ApplicationContextctx)throwsBeansException{Map<String,Object>serviceBeanMap=ctx.getBeansWithAnnotation(RpcService.class);for(ObjectserviceBean:serviceBeanMap.values()){try{MethodMethodmethod=serviceBean.getClass().getMethod("hello",newClass[]{String.class});Obj

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论