protobuf是谷歌的Protocol Buffers的简称,用于结构化数据和字节码之间互相转换(序列化、反序列化),一般应用于网络传输,可支持多种编程语言。
protobuf如何使用这里不再介绍,本文主要介绍在MINA、Netty、Twisted中如何使用protobuf,不了解protobuf的同学可以去参考我的另一篇博文。
在前面的一篇博文中,有介绍到一种用一个固定为4字节的前缀Header来指定Body的字节数的一种消息分割方式,在这里同样要使用到。只是其中Body的内容不再是字符串,而是protobuf字节码。
在处理业务逻辑时,肯定不希望还要对数据进行序列化和反序列化,而是希望直接操作一个对象,那么就需要有相应的编码器和解码器,将序列化和反序列化的逻辑写在编码器和解码器中。有关编码器和解码器的实现,上一篇博文中有介绍。
Netty包中已经自带针对protobuf的编码器和解码器,那么就不用再自己去实现了。而MINA、Twisted还需要自己去实现protobuf的编码器和解码器。
这里定义一个protobuf数据结构,用于描述一个学生的信息,保存为StudentMsg.proto文件:
message Student {
// ID
required int32 id = 1;
// 姓名
required string name = 2;
// email
optional string email = 3;
// 朋友
repeated string friends = 4;
}
用StudentMsg.proto分别生成Java和Python代码,将代码加入到相应的项目中。生成的代码就不再贴上来了。
下面分别介绍在Netty、MINA、Twisted如何使用protobuf来传输Student信息。
Netty:
Netty自带protobuf的编码器和解码器,分别是ProtobufEncoder和ProtobufDecoder。需要注意的是,ProtobufEncoder和ProtobufDecoder只负责protobuf的序列化和反序列化,而处理消息Header前缀和消息分割的还需要LengthFieldBasedFrameDecoder和LengthFieldPrepender。LengthFieldBasedFrameDecoder即用于解析消息Header前缀,根据Header中指定的Body字节数截取Body,LengthFieldPrepender用于在wirte消息时在消息前面添加一个Header前缀来指定Body字节数。
public class TcpServer {
public static void main(String[] args) throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch)
throws Exception {
ChannelPipeline pipeline = ch.pipeline();
// 负责通过4字节Header指定的Body长度将消息切割
pipeline.addLast("frameDecoder",
new LengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4));
// 负责将frameDecoder处理后的完整的一条消息的protobuf字节码转成Student对象
pipeline.addLast("protobufDecoder",
new ProtobufDecoder(StudentMsg.Student.getDefaultInstance()));
// 负责将写入的字节码加上4字节Header前缀来指定Body长度
pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
// 负责将Student对象转成protobuf字节码
pipeline.addLast("protobufEncoder", new ProtobufEncoder());
pipeline.addLast(new TcpServerHandler());
}
});
ChannelFuture f = b.bind(8080).sync();
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
}
处理事件时,接收和发送的参数直接就是Student对象:
public class TcpServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
// 读取客户端传过来的Student对象
StudentMsg.Student student = (StudentMsg.Student) msg;
System.out.println("ID:" + student.getId());
System.out.println("Name:" + student.getName());
System.out.println("Email:" + student.getEmail());
System.out.println("Friends:");
List<String> friends = student.getFriendsList();
for(String friend : friends) {
System.out.println(friend);
}
// 新建一个Student对象传到客户端
StudentMsg.Student.Builder builder = StudentMsg.Student.newBuilder();
builder.setId(9);
builder.setName("服务器");
builder.setEmail("123@abc.com");
builder.addFriends("X");
builder.addFriends("Y");
StudentMsg.Student student2 = builder.build();
ctx.writeAndFlush(student2);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
MINA:
在MINA中没有针对protobuf的编码器和解码器,但是可以自己实现一个功能和Netty一样的编码器和解码器。
编码器:
public class MinaProtobufEncoder extends ProtocolEncoderAdapter {
@Override
public