(中级篇 NettyNIO编解码开发)第七章-java序列化
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了(中级篇 NettyNIO编解码开发)第七章-java序列化,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含15062字,纯文字阅读大概需要22分钟。
内容图文
相信大多数Java程序员接触到的第一种序列化或者编解码技术就是.Java的默认序列化,只需要序列化的POJO对象实现java.io.Serializable接口,根据实际情况生成序列ID,
这个类就能够通过java.io.Objectlnput和java.io.ObjectOutput序列化和反序列化。
不需要考虑跨语言调用,对序列化的性能也没有苛刻的要求时,Java默认的序列化机制是最明智的选择之一。正因为此,虽然Java序列化机制存在着一些弊病,依然得到了广泛的应用。
本章主要内容包括:
1。NettyJava序列化服务端开发
2。NettyJava序列化客户端开发
3.运行Java序列化应用例程
7.1 NettyJava序列化服务端开发
服务端开发的场景如下:Netty 服务端接收到客户端的用户订购请求消息,消息定义
如表7-1所示。
7-1 NettyJava序列化订购请求POJO类定义
1 package lqy6_serializablePojo_127; 2 3 import java.io.Serializable; 4 /** 5 * @author Lilinfeng 6 * @date 2014年2月23日 7 * @version 1.0 8 */ 9 public class SubscribeReq implements Serializable { 10 11/** 12 * 默认的序列号ID 13*/ 14privatestaticfinallong serialVersionUID = 1L; 15 16privateint subReqID; 17 18private String userName; 19 20private String productName; 21 22private String phoneNumber; 23 24private String address; 25 26/** 27 * @return the subReqID 28*/ 29publicfinalint getSubReqID() { 30return subReqID; 31 } 32 33/** 34 * @param subReqID 35 * the subReqID to set 36*/ 37publicfinalvoid setSubReqID(int subReqID) { 38this.subReqID = subReqID; 39 } 40 41/** 42 * @return the userName 43*/ 44publicfinal String getUserName() { 45return userName; 46 } 47 48/** 49 * @param userName 50 * the userName to set 51*/ 52publicfinalvoid setUserName(String userName) { 53this.userName = userName; 54 } 55 56/** 57 * @return the productName 58*/ 59publicfinal String getProductName() { 60return productName; 61 } 62 63/** 64 * @param productName 65 * the productName to set 66*/ 67publicfinalvoid setProductName(String productName) { 68this.productName = productName; 69 } 70 71/** 72 * @return the phoneNumber 73*/ 74publicfinal String getPhoneNumber() { 75return phoneNumber; 76 } 77 78/** 79 * @param phoneNumber 80 * the phoneNumber to set 81*/ 82publicfinalvoid setPhoneNumber(String phoneNumber) { 83this.phoneNumber = phoneNumber; 84 } 85 86/** 87 * @return the address 88*/ 89publicfinal String getAddress() { 90return address; 91 } 92 93/** 94 * @param address 95 * the address to set 96*/ 97publicfinalvoid setAddress(String address) { 98this.address = address; 99 } 100101/*102 * (non-Javadoc) 103 * 104 * @see java.lang.Object#toString() 105*/106 @Override 107public String toString() { 108return "SubscribeReq [subReqID=" + subReqID + ", userName=" + userName 109 + ", productName=" + productName + ", phoneNumber=" 110 + phoneNumber + ", address=" + address + "]"; 111 } 112 }
SubscribeReq是个普通的JOJO对象,需要强调的有两点。
(1)第9行实现Serializable接口;
(2)第14行自动生成默认的序列化ID;
下面继续看订购应答POJO类。
NettyJava序列化订购应答POJO类定义
package lqy6_serializablePojo_127; import java.io.Serializable; /** * @author Lilinfeng * @date 2014年2月23日 * @version 1.0 */ public class SubscribeResp implements Serializable { /** * 默认序列ID */privatestaticfinallong serialVersionUID = 1L; privateint subReqID; privateint respCode; private String desc; /** * @return the subReqID */publicfinalint getSubReqID() { return subReqID; } /** * @param subReqID * the subReqID to set */publicfinalvoid setSubReqID(int subReqID) { this.subReqID = subReqID; } /** * @return the respCode */publicfinalint getRespCode() { return respCode; } /** * @param respCode * the respCode to set */publicfinalvoid setRespCode(int respCode) { this.respCode = respCode; } /** * @return the desc */publicfinal String getDesc() { return desc; } /** * @param desc * the desc to set */publicfinalvoid setDesc(String desc) { this.desc = desc; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return "SubscribeResp [subReqID=" + subReqID + ", respCode=" + respCode + ", desc=" + desc + "]"; } }
NettyJava序列化订购服务端主函数SubReqServer
1 package lqy6_serializableNetty_127; 2 3 import io.netty.bootstrap.ServerBootstrap; 4 import io.netty.channel.ChannelFuture; 5 import io.netty.channel.ChannelInitializer; 6 import io.netty.channel.ChannelOption; 7 import io.netty.channel.EventLoopGroup; 8 import io.netty.channel.nio.NioEventLoopGroup; 9 import io.netty.channel.socket.SocketChannel; 10 import io.netty.channel.socket.nio.NioServerSocketChannel; 11 import io.netty.handler.codec.serialization.ClassResolvers; 12 import io.netty.handler.codec.serialization.ObjectDecoder; 13 import io.netty.handler.codec.serialization.ObjectEncoder; 14 import io.netty.handler.logging.LogLevel; 15 import io.netty.handler.logging.LoggingHandler; 16 17 /** 18 * @author lilinfeng 19 * @date 2014年2月14日 20 * @version 1.0 21 */ 22 public class SubReqServer { 23 public void bind(int port) throws Exception { 24// 配置服务端的NIO线程组25 EventLoopGroup bossGroup = new NioEventLoopGroup(); 26 EventLoopGroup workerGroup = new NioEventLoopGroup(); 27try { 28 ServerBootstrap b = new ServerBootstrap(); 29 b.group(bossGroup, workerGroup) 30 .channel(NioServerSocketChannel.class) 31 .option(ChannelOption.SO_BACKLOG, 100) 32 .handler(new LoggingHandler(LogLevel.INFO)) 33 .childHandler(new ChannelInitializer<SocketChannel>() { 34 @Override 35publicvoid initChannel(SocketChannel ch) { 36 ch.pipeline() 37 .addLast( 38new ObjectDecoder( 39 1024 * 1024, 40 ClassResolvers 41 .weakCachingConcurrentResolver(this .getClass() 42 .getClassLoader()))); 43 ch.pipeline().addLast(new ObjectEncoder()); 44 ch.pipeline().addLast(new SubReqServerHandler()); 45 } 46 }); 4748// 绑定端口,同步等待成功49 ChannelFuture f = b.bind(port).sync(); 5051// 等待服务端监听端口关闭52 f.channel().closeFuture().sync(); 53 } finally { 54// 优雅退出,释放线程池资源55 bossGroup.shutdownGracefully(); 56 workerGroup.shutdownGracefully(); 57 } 58 } 5960publicstaticvoid main(String[] args) throws Exception { 61int port = 8080; 62if (args != null && args.length > 0) { 63try { 64 port = Integer.valueOf(args[0]); 65 } catch (NumberFormatException e) { 66// 采用默认值67 } 68 } 69new SubReqServer().bind(port); 70 } 71 }
从35行开始进行分析。首先创建了一个新的ObjectDecoder,它负责对实现Serializable的POJ0对象进行解码,它有多个构造函数,支持不同的ClassResolver,在此我们使用weakCachingConcurrentResolver创建线程安全的WeakReferenceMap对类加载器进行缓存,它支持多线程并发访问,当虚拟机内存不足时,会释放缓存中的内存,防止内存泄漏。为了防止异常码流和解码错位导致的内存溢出,这里将单个对象最大序列化后的字节数组长度设置为IM,作为例程它已经足够使用。
第43行新增了一个ObjectEncoder,它可以在消息发送的时候自动将实现Serializable的POJO对象进行编码,因此用户无须亲自对对象进行手工序列化,只需要关注自己的业务应辑处理即可,对象序列化和反序列化都由Netty的对象编解码器搞定。
第44行将订购处理SubReqServerHandler添加到ChannelPipeline的尾部用于业务逻辑处理,
下面我们看下SubReqServerHandler是如何实现的。
1 package lqy6_serializableNetty_127; 2 3 import io.netty.channel.ChannelHandler.Sharable; 4 import io.netty.channel.ChannelHandlerAdapter; 5 import io.netty.channel.ChannelHandlerContext; 6 import lqy6_serializablePojo_127.SubscribeReq; 7 import lqy6_serializablePojo_127.SubscribeResp; 8 9 /** 10 * @author lilinfeng 11 * @date 2014年2月14日 12 * @version 1.0 13 */ 14 @Sharable 15 public class SubReqServerHandler extends ChannelHandlerAdapter { 1617 @Override 18publicvoid channelRead(ChannelHandlerContext ctx, Object msg) 19throws Exception { 20 SubscribeReq req = (SubscribeReq) msg; 21if ("Lilinfeng".equalsIgnoreCase(req.getUserName())) { 22 System.out.println("Service accept client subscrib req : [" 23 + req.toString() + "]"); 24 ctx.writeAndFlush(resp(req.getSubReqID())); 25 } 26 } 2728private SubscribeResp resp(int subReqID) { 29 SubscribeResp resp = new SubscribeResp(); 30 resp.setSubReqID(subReqID); 31 resp.setRespCode(0); 32 resp.setDesc("Netty book order succeed, 3 days later, sent to the designated address"); 33return resp; 34 } 3536 @Override 37publicvoid exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 38 cause.printStackTrace(); 39 ctx.close();// 发生异常,关闭链路40 } 41 }
经过解码器handlerObjectDecoder的解码,SubReqServerHandler 接收到的请求消息已经被自动解码为SubscribeReq对象,可以直接使用。
第21行对订购者的用户名进行合法性校验,校验通过后打印订购请求消息,构造订购成功应答消息立即发送给客户端。
下面继续进行产品订购客户端的开发
7.2 Java序列化Netty客户端开发
客户端的设计思路如下。
(1)创建客户端的时候将Netty对象解码器和编码器添加到ChannelPipeline;
(2)链路被激活的时候构造订购请求消息发送,为了检验Netty的Java序列化功能是否支持TCP粘包/拆包,客户端一次构造10条订购请求,最后一次性发送给服务端:
(3)客户端订购处理handle将接收到的订购响应消息打印出来。面我们具体看下客户端的代码实现。
客户踹开发例程
7-5 NettyJava序列化产品订购客户端
1 package lqy6_serializableNetty_127; 2 3 import io.netty.bootstrap.Bootstrap; 4 import io.netty.channel.ChannelFuture; 5 import io.netty.channel.ChannelInitializer; 6 import io.netty.channel.ChannelOption; 7 import io.netty.channel.EventLoopGroup; 8 import io.netty.channel.nio.NioEventLoopGroup; 9 import io.netty.channel.socket.SocketChannel; 10 import io.netty.channel.socket.nio.NioSocketChannel; 11 import io.netty.handler.codec.serialization.ClassResolvers; 12 import io.netty.handler.codec.serialization.ObjectDecoder; 13 import io.netty.handler.codec.serialization.ObjectEncoder; 14 15 /** 16 * @author lilinfeng 17 * @date 2014年2月14日 18 * @version 1.0 19 */ 20 public class SubReqClient { 21 public void connect(int port, String host) throws Exception { 22// 配置客户端NIO线程组23 EventLoopGroup group = new NioEventLoopGroup(); 24try { 25 Bootstrap b = new Bootstrap(); 26 b.group(group).channel(NioSocketChannel.class) 27 .option(ChannelOption.TCP_NODELAY, true) 28 .handler(new ChannelInitializer<SocketChannel>() { 29 @Override 30publicvoid initChannel(SocketChannel ch) 31throws Exception { 32 ch.pipeline().addLast( 33new ObjectDecoder(1024, ClassResolvers 34 .cacheDisabled(this.getClass() . 35 getClassLoader()))); 36 ch.pipeline().addLast(new ObjectEncoder()); 37 ch.pipeline().addLast(new SubReqClientHandler()); 38 } 39 }); 4041// 发起异步连接操作42 ChannelFuture f = b.connect(host, port).sync(); 4344// 当代客户端链路关闭45 f.channel().closeFuture().sync(); 46 } finally { 47// 优雅退出,释放NIO线程组48 group.shutdownGracefully(); 49 } 50 } 5152/**53 * @param args 54 * @throws Exception 55*/56publicstaticvoid main(String[] args) throws Exception { 57int port = 8080; 58if (args != null && args.length > 0) { 59try { 60 port = Integer.valueOf(args[0]); 61 } catch (NumberFormatException e) { 62// 采用默认值63 } 64 } 65new SubReqClient().connect(port, "127.0.0.1"); 66 } 67 }
第32行,我们禁止对类加载器进行缓存,它在基于OSGi的动态模块化编程中经常使用。由于OSGi的bundle可以进行热部署和热升级,当某个bundle升级后,它对应的类加载器也将一起升级,因此在动态模块化编程过程中,很少对类加载器进行缓存,因为它随时可能会发生变化
下面继续看下SubReqClientHandler的实现。
1 package lqy6_serializableNetty_127; 2 3 import io.netty.channel.ChannelHandlerAdapter; 4 import io.netty.channel.ChannelHandlerContext; 5 import lqy6_serializablePojo_127.SubscribeReq; 6 7 8 /** 9 * @author lilinfeng 10 * @date 2014年2月14日 11 * @version 1.0 12 */ 13 public class SubReqClientHandler extends ChannelHandlerAdapter { 14/**15 * Creates a client-side handler. 16*/17public SubReqClientHandler() { 18 } 1920 @Override 21publicvoid channelActive(ChannelHandlerContext ctx) { 22for (int i = 0; i < 10; i++) { 23 ctx.write(subReq(i)); 24 } 25 ctx.flush(); 26 } 2728private SubscribeReq subReq(int i) { 29 SubscribeReq req = new SubscribeReq(); 30 req.setAddress("南京市雨花台区软件大道101号华为基地"); 31 req.setPhoneNumber("138xxxxxxxxx"); 32 req.setProductName("Netty 最佳实践和原理分析"); 33 req.setSubReqID(i); 34 req.setUserName("Lilinfeng"); 35return req; 36 } 3738 @Override 39publicvoid channelRead(ChannelHandlerContext ctx, Object msg) 40throws Exception { 41 System.out.println("Receive server response : [" + msg + "]"); 42 } 4344 @Override 45publicvoid channelReadComplete(ChannelHandlerContext ctx) throws Exception { 46 ctx.flush(); 47 } 4849 @Override 50publicvoid exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 51 cause.printStackTrace(); 52 ctx.close(); 53 } 54 }
第22~25行,在链路激活的时候循环构造10条订购请求消息,最后一次性地发送给服务端。由于对象解码器已经对订购请求应答消息进行了自动解码,此,SubReqClientHandler接收到的消息已经是解码成功后的订购应答消息。
下面的小节将执行我们前面开发的订购请求客户端和服务端,看下执行结果是否符合设计预期。
7.3 运行结果
运行Java例程
首先运行服务端,然后运行客户端,运行结果如下。服务端运行结果如下。
1 Service accept client subscrib req : [SubscribeReq [subReqID=0, userName=Lilinfeng, productName=Netty 最佳实践和原理分析, phoneNumber=138xxxxxxxxx, address=南京市雨花台区软件大道101号华为基地]] 2 Service accept client subscrib req : [SubscribeReq [subReqID=1, userName=Lilinfeng, productName=Netty 最佳实践和原理分析, phoneNumber=138xxxxxxxxx, address=南京市雨花台区软件大道101号华为基地]] 3 Service accept client subscrib req : [SubscribeReq [subReqID=2, userName=Lilinfeng, productName=Netty 最佳实践和原理分析, phoneNumber=138xxxxxxxxx, address=南京市雨花台区软件大道101号华为基地]] 4 Service accept client subscrib req : [SubscribeReq [subReqID=3, userName=Lilinfeng, productName=Netty 最佳实践和原理分析, phoneNumber=138xxxxxxxxx, address=南京市雨花台区软件大道101号华为基地]] 5 Service accept client subscrib req : [SubscribeReq [subReqID=4, userName=Lilinfeng, productName=Netty 最佳实践和原理分析, phoneNumber=138xxxxxxxxx, address=南京市雨花台区软件大道101号华为基地]] 6 Service accept client subscrib req : [SubscribeReq [subReqID=5, userName=Lilinfeng, productName=Netty 最佳实践和原理分析, phoneNumber=138xxxxxxxxx, address=南京市雨花台区软件大道101号华为基地]] 7 Service accept client subscrib req : [SubscribeReq [subReqID=6, userName=Lilinfeng, productName=Netty 最佳实践和原理分析, phoneNumber=138xxxxxxxxx, address=南京市雨花台区软件大道101号华为基地]] 8 Service accept client subscrib req : [SubscribeReq [subReqID=7, userName=Lilinfeng, productName=Netty 最佳实践和原理分析, phoneNumber=138xxxxxxxxx, address=南京市雨花台区软件大道101号华为基地]] 9 Service accept client subscrib req : [SubscribeReq [subReqID=8, userName=Lilinfeng, productName=Netty 最佳实践和原理分析, phoneNumber=138xxxxxxxxx, address=南京市雨花台区软件大道101号华为基地]] 10 Service accept client subscrib req : [SubscribeReq [subReqID=9, userName=Lilinfeng, productName=Netty 最佳实践和原理分析, phoneNumber=138xxxxxxxxx, address=南京市雨花台区软件大道101号华为基地]]
尽管客户端一次批量发送了10条订购请求消息,TCP会对请求消息进行粘包和拆包,但是并没有影响最终的运行结果:服务端成功收到了10条订购请求消息,与客户端发淫的一致。
客户端运行结果如下。
1 Receive server response : [SubscribeResp [subReqID=0, respCode=0, desc=Netty book order succeed, 3 days later, sent to the designated address]] 2 Receive server response : [SubscribeResp [subReqID=1, respCode=0, desc=Netty book order succeed, 3 days later, sent to the designated address]] 3 Receive server response : [SubscribeResp [subReqID=2, respCode=0, desc=Netty book order succeed, 3 days later, sent to the designated address]] 4 Receive server response : [SubscribeResp [subReqID=3, respCode=0, desc=Netty book order succeed, 3 days later, sent to the designated address]] 5 Receive server response : [SubscribeResp [subReqID=4, respCode=0, desc=Netty book order succeed, 3 days later, sent to the designated address]] 6 Receive server response : [SubscribeResp [subReqID=5, respCode=0, desc=Netty book order succeed, 3 days later, sent to the designated address]] 7 Receive server response : [SubscribeResp [subReqID=6, respCode=0, desc=Netty book order succeed, 3 days later, sent to the designated address]] 8 Receive server response : [SubscribeResp [subReqID=7, respCode=0, desc=Netty book order succeed, 3 days later, sent to the designated address]] 9 Receive server response : [SubscribeResp [subReqID=8, respCode=0, desc=Netty book order succeed, 3 days later, sent to the designated address]] 10 Receive server response : [SubscribeResp [subReqID=9, respCode=0, desc=Netty book order succeed, 3 days later, sent to the designated address]]
客户端接收到了10条订购应答消息,Netty的ObjectEncoder编码器可以自动对订购应答消息进行序列化,然后发送给客户端,客户端的ObjectDecoder对码流进行反序列化,获得订购请求应答消息。
总结
本章介绍了如何利用Netty提供的ObjectEncoder编码器和ObjectDecoder解码器实现对普边POJO对象的序列化。通过订购图书例程,我们学习了服务端和客户端的开发,并且模拟了TCP粘包/拆包场景,对运行结果进行了分析。
通过使用Netty的Java序列化编解码handler,用户通过短短的几行代码,就能完成POJO的序列化和反序列化。在业务处理ba:ndler中,用户只需要将精力聚焦在业务逻辑的实现上F不需要关心底层的编解码细节,这极大地提升了开发效率。
下一章我们继续学习谷歌的Protob时,看在Netty 中如何使用Protob?uf 实现对POJO
对象的自动编解码。
原文:http://www.cnblogs.com/crazylqy/p/4901253.html
内容总结
以上是互联网集市为您收集整理的(中级篇 NettyNIO编解码开发)第七章-java序列化全部内容,希望文章能够帮你解决(中级篇 NettyNIO编解码开发)第七章-java序列化所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。