下面是官网给的解释:
Protocol buffers are a language-neutral, platform-neutral extensible mechanism for serializing structured data. – think XML, but smaller, faster, and simpler.
协议缓冲区是一种和语言无关、平台无关的可扩展机制,用于序列化结构化的数据。相比于xml,它更小,更快,更简单。数据缓冲区经常使用语通讯协议和数据存储。html
序列化测试对比:
Ser Time + Deser Time(ns)java
下面两个网站是效率测试实验:git
参考个人另外一篇文章:Google Protocol Buffer 的使用(一)github
syntax = "proto3"; package com.netty.protobuf; option java_outer_classname = "UserInfoProto"; //用户信息 message UserInfo{ //姓名 string name = 1; //住址 repeated Address address= 2; //年龄 uint32 age = 3; } //用户经常使用住址 message Address{ string addressname = 1; uint32 adressno = 2; }
@Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); //protobuf解码器 pipeline.addLast(new ProtobufVarint32FrameDecoder()); pipeline.addLast(new ProtobufDecoder(UserInfoProto.UserInfo.getDefaultInstance())); //protobuf编码器 pipeline.addLast(new ProtobufVarint32LengthFieldPrepender()); pipeline.addLast(new ProtobufEncoder()); pipeline.addLast(new NettyServerHandler()); }
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { LOGGER.info("client {} connected.", ctx.channel().remoteAddress()); UserInfoProto.UserInfo user = UserInfoProto.UserInfo.newBuilder() .setName("server") .setAge(18) .addAddress( UserInfoProto.Address.newBuilder() .setAddressname("beijing 001") .setAdressno(911)) .build(); ctx.writeAndFlush(user); }
private int count = 0; @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { UserInfoProto.UserInfo message = (UserInfoProto.UserInfo) msg; LOGGER.info("server received message {}:{}", ++count, message); }
这里咱们只是简单使用了netty自带的ProtobufVarint32FrameDecoder解码器来处理读半包问题,咱们还能够本身继承ByteToMessageDecoder类实现一个定制化的解码器。好比咱们使用Java客户端和C++服务器经过protobuf协议来通讯时,就须要本身实现,同时还须要考虑大端、小端模式的转换问题。服务器