当进行远程跨进程服务调用时,需要把被传输的Java对象编码为字节数组或者ByteBuffer对象。而当远程服务读取到ByteBuffer对象或者字节数组时,需要将其解码为发送时的Java对象。这被称为Java对象编解码技术。而我们常见得Java序列化仅仅是Java编解码技术的一种,由于java序列化有以下缺点:
- 无法跨语言
- 序列化后的码流太大
- 序列化性能太低
因此衍生了多种编解码技术和框架。
如何评判一个编解码框架的优劣
- 是否支持跨语言,支持的语言种类是否丰富
- 编码后的码流大小
- 编解码的性能
- 类库是否小巧,API使用是否方便
- 使用者需要手工开发的工作量和难度
在同等情况下,编码后的字节数组越大,存储的时候就越占空间,存储的硬件成本就越高,并且在网络传输时更占带宽,导致系统的吞吐量降低。
业界主流的编解码框架
- Google的Protobuf
- Facebook的Thrift
- JBoss Marshalling
后面会介绍以上三个编解码框架的使用。
MessagePack编解码
MessagePack的特点:
- 编解码高效,性能高
- 序列化之后的码流小
- 支持跨语言
使用
如果是使用Maven开发,先添加依赖:
<dependencies>
...
<dependency>
<groupId>org.msgpack</groupId>
<artifactId>msgpack</artifactId>
<version>${msgpack.version}</version>
</dependency>
...
</dependencies>
api使用:
// Create serialize objects.
List<String> src = new ArrayList<String>();
src.add("msgpack");
src.add("kumofs");
src.add("viver");
MessagePack msgpack = new MessagePack();
// Serialize
byte[] raw = msgpack.write(src);
// Deserialize directly using a template
List<String> dst1 = msgpack.read(raw, Templates.tList(Templates.TString));
System.out.println(dst1.get(0));
System.out.println(dst1.get(1));
System.out.println(dst1.get(2));
在Netty中使用实践
编码器开发
编码器MsgpackEncoder继承MessageToByteEncoder,负责将Object类型的POJO对象编码为byte数组,然后写入到ByteBuf中。
package com.ph.Netty;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.msgpack.MessagePack;
/**
* msg编码器
* Create by PH on 2018/11/7
*/
public class MsgpackEncoder extends MessageToByteEncoder<Object> {
/**
*
* @param arg0
* @param arg1 要发送的对象
* @param arg2 发送缓冲区
* @throws Exception
*/
protected void encode(ChannelHandlerContext arg0, Object arg1, ByteBuf arg2) throws Exception {
MessagePack msgpack = new MessagePack();
byte[] raw = msgpack.write(arg1);
arg2.writeBytes(raw);
}
}
解码器开发
package com.ph.Netty;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import org.msgpack.MessagePack;
import java.util.List;
/**
* MessagePack解码器
* Create by PH on 2018/11/7
*/
public class MsgpackDecoder extends MessageToMessageDecoder<ByteBuf> {
/**
*
* @param arg0
* @param arg1 接受到的数据
* @param arg2 解码后的数据
* @throws Exception
*/
protected void decode(ChannelHandlerContext arg0, ByteBuf arg1, List<Object> arg2) throws Exception {
final int length = arg1.readableBytes();
final byte[] array = new byte[length];
//获取要解码的byte数组
arg1.getBytes(arg1.readerIndex(), array, 0, length);
MessagePack msgpack = new MessagePack();
//将解码后的对象加入到解码列表中
arg2.add(msgpack.read(array));
}
}
首先从数据报arg1中获取需要解码的byte数组,然后调用MessagePack的read方法将其反序列化为Object对象,将解码后的对象加入到解码列表arg2中。
需要序列化的POJO类
注意需要加上@Message注解。
package com.ph.Netty;
import org.msgpack.annotation.Message;
/**
* Create by PH on 2018/11/7
*/
@Message
public class UserInfo {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
LengthFieldPrepender和LengthFieldBasedFrameDecoder介绍
为了防止粘包/半包,除了之前介绍的解决策略外,其实最常用的是在消息头中新增报文长度字段,利用该字段进行半包的编解码。详细说明看这里
Netty服务端
package com.ph.Netty;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
/**
* Create by PH on 2018/11/7
*/
public class NettyServer {
public static void main(String[] args) throws Exception {
int port = 8080;
if(args !=null && args.length>0) {
try {
port = Integer.valueOf(args[0]);
}catch (NumberFormatException e) {
//采用默认值
}
}
new NettyServer().bind(port);
}
public void bind(int port) throws Exception{
//NioEventLoopGroup是一个线程组,包含了一组NIO线程,专门用于网络事件的处理,实际上他们就是Reactor线程组
//bossGroup仅接收客户端连接,不做复杂的逻辑处理,为了尽可能减少资源的占用,取值越小越好
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
//用于进行SocketChannel的网络读写
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
//是Netty用于启动NIO服务端的辅助启动类,目的是降低服务端的开发复杂度
ServerBootstrap b = new ServerBootstrap();
//配置NIO服务端
b.group(bossGroup, workerGroup)
//指定使用NioServerSocketChannel产生一个Channel用来接收连接,他的功能对应于JDK
// NIO类库中的ServerSocketChannel类。
.channel(NioServerSocketChannel.class)
//BACKLOG用于构造服务端套接字ServerSocket对象,标识当服务器请求处理线程全满时,
// 用于临时存放已完成三次握手的请求的队列的最大长度。如果未设置或所设置的值小于1,
// Java将使用默认值50。
.option(ChannelOption.SO_BACKLOG, 1024)
//绑定I/O事件处理类,作用类似于Reactor模式中的Handler类,主要用于处理网络I/O事件
.childHandler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel arg0) throws Exception {
arg0.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(65535, 0, 2, 0, 2));
arg0.pipeline().addLast("decoder", new MsgpackDecoder());
arg0.pipeline().addLast("frameEncoder", new LengthFieldPrepender(2));
arg0.pipeline().addLast("encoder", new MsgpackEncoder());
arg0.pipeline().addLast(new ServerHandler());
}
});
//绑定端口,同步等待绑定操作完成,完成后返回一个ChannelFuture,用于异步操作的通知回调
ChannelFuture f = b.bind(port).sync();
//等待服务端监听端口关闭之后才退出main函数
f.channel().closeFuture().sync();
} finally {
//退出,释放线程池资源
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
/**
* ChannelInboundHandlerAdapter实现自ChannelInboundHandler
* ChannelInboundHandler提供了不同的事件处理方法你可以重写
*/
class ServerHandler extends ChannelInboundHandlerAdapter {
/**
* 接受客户端发送的消息
* @param ctx
* @param msg
* @throws Exception
*/
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("Server receive: " + msg);
ctx.write(msg);
}
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//将消息发送队列中的消息写入到SocketChannel中发送给对方
ctx.flush();
}
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
//当发生异常时释放资源
ctx.close();
}
}
Netty客户端
package com.ph.Netty;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
/**
* Create by PH on 2018/11/7
*/
public class NettyClient {
public static void main(String[] args) throws Exception {
int port = 8080;
if (args != null && args.length > 0) {
try {
port = Integer.valueOf(args[0]);
} catch (NumberFormatException e) {
//采用默认值
}
}
new NettyClient().connect(port, "127.0.0.1", 100);
}
public void connect(int port, String host, int sendNumber) throws Exception{
//配置客户端NIO线程组
EventLoopGroup group = new NioEventLoopGroup();
try{
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
public void initChannel(SocketChannel ch) throws Exception{
ch.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(65535, 0, 2, 0, 2));
ch.pipeline().addLast("decoder", new MsgpackDecoder());
ch.pipeline().addLast("frameEncoder", new LengthFieldPrepender(2));
ch.pipeline().addLast("encoder", new MsgpackEncoder());
ch.pipeline().addLast(new ClientHandler(sendNumber));
}
});
//发起异步连接操作
ChannelFuture f = b.connect(host, port).sync();
//等待客户端链路关闭
f.channel().closeFuture().sync();
}finally {
group.shutdownGracefully();
}
}
}
class ClientHandler extends ChannelInboundHandlerAdapter {
private int sendNumber;
public ClientHandler(int sendNumber) {
this.sendNumber = sendNumber;
}
/**
* 当客户端和服务端TCP链路建立成功之后,Netty的NIO线程会调用此方法
* @param ctx
*/
public void channelActive(ChannelHandlerContext ctx) {
UserInfo userInfo = null;
for (int i=0;i<sendNumber;i++) {
userInfo = new UserInfo();
userInfo.setAge(i);
userInfo.setName("NAME: " + i);
ctx.write(userInfo);
}
ctx.flush();
}
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception{
System.out.println("Client receive :" + msg);
}
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ctx.close();
}
}