您的位置:首页 > 编程语言 > Java开发

<Netty>(十三)(中级篇)java序列化(有缺陷的,但是有一定的应用)

2018-03-13 20:29 537 查看

 

相信大多数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      */
14     private static final long serialVersionUID = 1L;
15
16     private int subReqID;
17
18     private String userName;
19
20     private String productName;
21
22     private String phoneNumber;
23
24     private String address;
25
26     /**
27      * @return the subReqID
28      */
29     public final int getSubReqID() {
30     return subReqID;
31     }
32
33     /**
34      * @param subReqID
35      *            the subReqID to set
36      */
37     public final void setSubReqID(int subReqID) {
38     this.subReqID = subReqID;
39     }
40
41     /**
42      * @return the userName
43      */
44     public final String getUserName() {
45     return userName;
46     }
47
48     /**
49      * @param userName
50      *            the userName to set
51      */
52     public final void setUserName(String userName) {
53     this.userName = userName;
54     }
55
56     /**
57      * @return the productName
58      */
59     public final String getProductName() {
60     return productName;
61     }
62
63     /**
64      * @param productName
65      *            the productName to set
66      */
67     public final void setProductName(String productName) {
68     this.productName = productName;
69     }
70
71     /**
72      * @return the phoneNumber
73      */
74     public final String getPhoneNumber() {
75     return phoneNumber;
76     }
77
78     /**
79      * @param phoneNumber
80      *            the phoneNumber to set
81      */
82     public final void setPhoneNumber(String phoneNumber) {
83     this.phoneNumber = phoneNumber;
84     }
85
86     /**
87      * @return the address
88      */
89     public final String getAddress() {
90     return address;
91     }
92
93     /**
94      * @param address
95      *            the address to set
96      */
97     public final void setAddress(String address) {
98     this.address = address;
99     }
100
101     /*
102      * (non-Javadoc)
103      *
104      * @see java.lang.Object#toString()
105      */
106     @Override
107     public String toString() {
108     return "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类定义

1 package lqy6_serializablePojo_127;
2
3 import java.io.Serializable;
4
5 /**
6  * @author Lilinfeng
7  * @date 2014年2月23日
8  * @version 1.0
9  */
10 public class SubscribeResp implements Serializable {
11
12     /**
13      * 默认序列ID
14      */
15     private static final long serialVersionUID = 1L;
16
17     private int subReqID;
18
19     private int respCode;
20
21     private String desc;
22
23     /**
24      * @return the subReqID
25      */
26     public final int getSubReqID() {
27     return subReqID;
28     }
29
30     /**
31      * @param subReqID
32      *            the subReqID to set
33      */
34     public final void setSubReqID(int subReqID) {
35     this.subReqID = subReqID;
36     }
37
38     /**
39      * @return the respCode
40      */
41     public final int getRespCode() {
42     return respCode;
43     }
44
45     /**
46      * @param respCode
47      *            the respCode to set
48      */
49     public final void setRespCode(int respCode) {
50     this.respCode = respCode;
51     }
52
53     /**
54      * @return the desc
55      */
56     public final String getDesc() {
57     return desc;
58     }
59
60     /**
61      * @param desc
62      *            the desc to set
63      */
64     public final void setDesc(String desc) {
65     this.desc = desc;
66     }
67
68     /*
69      * (non-Javadoc)
70      *
71      * @see java.lang.Object#toString()
72      */
73     @Override
74     public String toString() {
75     return "SubscribeResp [subReqID=" + subReqID + ", respCode=" + respCode
76         + ", desc=" + desc + "]";
77     }
78
79 }

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();
27     try {
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
35             public void initChannel(SocketChannel ch) {
36                 ch.pipeline()
37                     .addLast(
38                         new 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             });
47
48         // 绑定端口,同步等待成功
49         ChannelFuture f = b.bind(port).sync();
50
51         // 等待服务端监听端口关闭
52         f.channel().closeFuture().sync();
53     } finally {
54         // 优雅退出,释放线程池资源
55         bossGroup.shutdownGracefully();
56         workerGroup.shutdownGracefully();
57     }
58     }
59
60     public static void main(String[] args) throws Exception {
61     int port = 8080;
62     if (args != null && args.length > 0) {
63         try {
64         port = Integer.valueOf(args[0]);
65         } catch (NumberFormatException e) {
66         // 采用默认值
67         }
68     }
69     new 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 {
16
17     @Override
18     public void channelRead(ChannelHandlerContext ctx, Object msg)
19         throws Exception {
20     SubscribeReq req = (SubscribeReq) msg;
21     if ("Lilinfeng".equalsIgnoreCase(req.getUserName())) {
22         System.out.println("Service accept client subscrib req : ["
23             + req.toString() + "]");
24         ctx.writeAndFlush(resp(req.getSubReqID()));
25     }
26     }
27
28     private 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");
33     return resp;
34     }
35
36     @Override
37     public void 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();
24     try {
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
30             public void initChannel(SocketChannel ch)
31                 throws Exception {
32                 ch.pipeline().addLast(
33                     new ObjectDecoder(1024, ClassResolvers
34                         .cacheDisabled(this.getClass() .
35                                 getClassLoader())));
36                 ch.pipeline().addLast(new ObjectEncoder());
37                 ch.pipeline().addLast(new SubReqClientHandler());
38             }
39             });
40
41         // 发起异步连接操作
42         ChannelFuture f = b.connect(host, port).sync();
43
44         // 当代客户端链路关闭
45         f.channel().closeFuture().sync();
46     } finally {
47         // 优雅退出,释放NIO线程组
48         group.shutdownGracefully();
49     }
50     }
51
52     /**
53      * @param args
54      * @throws Exception
55      */
56     public static void main(String[] args) throws Exception {
57     int port = 8080;
58     if (args != null && args.length > 0) {
59         try {
60         port = Integer.valueOf(args[0]);
61         } catch (NumberFormatException e) {
62         // 采用默认值
63         }
64     }
65     new 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      */
17     public SubReqClientHandler() {
18     }
19
20     @Override
21     public void channelActive(ChannelHandlerContext ctx) {
22     for (int i = 0; i < 10; i++) {
23         ctx.write(subReq(i));
24     }
25     ctx.flush();
26     }
27
28     private 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");
35     return req;
36     }
37
38     @Override
39     public void channelRead(ChannelHandlerContext ctx, Object msg)
40         throws Exception {
41     System.out.println("Receive server response : [" + msg + "]");
42     }
43
44     @Override
45     public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
46     ctx.flush();
47     }
48
49     @Override
50     public void 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
对象的自动编解码。

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐