1、Protobuf介绍
Protobuf是由谷歌开源而来,在谷歌内部久经考验。它将数据结构以.proto文件进行描述,通过代码生成工具可以生成对应数据结构的POJO对象和Protobuf相关的方法和属性。
特点如下:
-
结构化数据存储格式(XML,JSON等)
-
高效的编解码性能
-
语言无关、平台无关、扩展性好
相对于其它protobuf更具有优势
-
序列化后体积相比Json和XML很小,适合网络传输
-
支持跨平台多语言
-
消息格式升级和兼容性还不错
-
序列化反序列化速度很快,快于Json的处理速速
结论: 在一个需要大量的数据传输的场景中,如果数据量很大,那么选择protobuf可以明显的减少数据量,减少网络IO,从而减少网络传输所消耗的时间。
因而,对于打造一款高性能的通讯服务器来说,protobuf 传输格式,是最佳的解决方案。
2、如何使用?
安装protobuf插件
添加maven依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>netty-item</artifactId>
<groupId>com.suzhe</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>netty-basic</artifactId>
<properties>
<grpc.version>1.6.1</grpc.version>
<protobuf.version>3.3.0</protobuf.version>
</properties>
<dependencies>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.6.Final</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<!--protobuf start-->
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty</artifactId>
<version>${grpc.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>${grpc.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>${grpc.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>${protobuf.version}</version>
</dependency>
<!--protobuf end-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
<!--provided表明该包只在编译和测试的时候用-->
<scope>provided</scope>
</dependency>
<!--log-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.1.7</version>
</dependency>
</dependencies>
<build>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.5.0.Final</version>
</extension>
</extensions>
<plugins>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.5.0</version>
<configuration>
<protocArtifact>com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier}</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
创建目录proto,然后将该目录变为source root。
在该目录下创建person.proto文件
syntax = "proto3";
option java_outer_classname = "PersonDto";//指定生成的文件名
message Person{
int32 id = 1;
string name = 2;
int32 age = 3;
}
编译
这时候可以看到target已生成出对应的java类,将该类拷贝到指定的Java目录中。
3、protobuf在netty中的应用
netty已经帮我们内置了protobuf的编解码处理类了,服务端和客户端只需要引进对应的处理类即可。
服务端代码:
public class ProtobufEchoServer {
private int port;
private EventLoopGroup bossGroup;
private EventLoopGroup workGroup;
private ServerBootstrap b;
public ProtobufEchoServer(int port) {
this.port = port;
//第一个线程组是用于接收Client连接的
bossGroup = new NioEventLoopGroup(1);
//第二个线程组是用于消息的读写操作
workGroup = new NioEventLoopGroup(2);
//服务端辅助启动类
b = new ServerBootstrap();
b.group(bossGroup, workGroup)
//需要指定使用NioServerSocketChannel这种类型的通道
.channel(NioServerSocketChannel.class)
//向ChannelPipeline里添加业务处理handler
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//添加 ProtobufVarint32FrameDecoder 以分离数据帧,就是解决黏包和拆包问题
ch.pipeline().addLast(
new ProtobufVarint32FrameDecoder());
//添加ProtobufDecoder反序列化,将分离后的字节解码为实体对象
ch.pipeline().addLast(new ProtobufDecoder(
PersonDto.Person.getDefaultInstance()
));
// 用来添加报文长度字段
ch.pipeline().addLast(
new ProtobufVarint32LengthFieldPrepender());
//添加 ProtobufEncoder 进行序列化将实体类编码为字节
ch.pipeline().addLast(new ProtobufEncoder());
ch.pipeline().addLast(new ProtobufEchoServerInHandler());
}
});
}
/**
* 启动
* @throws InterruptedException
*/
public void start() throws InterruptedException {
try {
//绑定到端口,阻塞等待直到完成
b.bind(this.port).sync();
System.out.println("服务器启动成功");
} finally {
}
}
/**
* 资源优雅释放
*/
public void close() {
try {
if (bossGroup != null)
bossGroup.shutdownGracefully().sync();
if (workGroup != null)
workGroup.shutdownGracefully().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException, IOException {
int port = 9999;
ProtobufEchoServer echoServer = new ProtobufEchoServer(port);
try {
echoServer.start();
//防止主程序退出
System.in.read();
} finally {
echoServer.close();
}
}
}
服务端处理类:
public class ProtobufEchoServerInHandler extends SimpleChannelInboundHandler<PersonDto.Person> {
/**
* 服务端读取到网络数据后的处理
* @param ctx
* @param person
* @throws Exception
*/
@Override
public void channelRead0(ChannelHandlerContext ctx, PersonDto.Person person)
throws Exception {
System.out.println("CustomEchoServerInHandler:id=" + person.getId());
PersonDto.Person.Builder builder = PersonDto.Person.newBuilder();
builder.setId(person.getId());
builder.setName("hello");
builder.setAge(18);
ctx.writeAndFlush(builder.build());
}
/**
* exceptionCaught()事件处理方法当出现Throwable对象才会被调用
* 即当Netty由于IO错误或者处理器在处理事件时抛出的异常时
* @param ctx
* @param cause
* @throws Exception
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
cause.printStackTrace();
ctx.close();
}
}
客户端
public class ProtobufEchoClient {
private final int port;
private final String host;
private Channel channel;
private EventLoopGroup group;
private Bootstrap b;
public ProtobufEchoClient(String host, int port) {
this.host = host;
this.port = port;
//客户端启动辅助类
b = new Bootstrap();
//构建线程组 处理读写
group = new NioEventLoopGroup();
b.group(group)
//指明使用NIO进行网络通讯
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//添加 ProtobufVarint32FrameDecoder 以分离数据帧,就是解决黏包和拆包问题
ch.pipeline().addLast(
new ProtobufVarint32FrameDecoder());
//添加ProtobufDecoder反序列化,将分离后的字节解码为实体对象
ch.pipeline().addLast(new ProtobufDecoder(
PersonDto.Person.getDefaultInstance()
));
// 用来添加报文长度字段
ch.pipeline().addLast(
new ProtobufVarint32LengthFieldPrepender());
//添加 ProtobufEncoder 进行序列化将实体类编码为字节
ch.pipeline().addLast(new ProtobufEncoder());
ch.pipeline().addLast(new ProtobufEchoClientInHandler());
}
});
}
public void start() {
try {
//连接到远程节点,阻塞等待直到连接完成
ChannelFuture f = b.connect(new InetSocketAddress(host, port)).sync();
//同步获取channel(通道,实际上是对socket的封装支持读取和写入)
channel = f.sync().channel();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 发送消息
*
* @param person
* @return
*/
public boolean send(PersonDto.Person person) {
channel.writeAndFlush(person);
return true;
}
/**
* 关闭释放资源
*/
public void close() {
try {
if (group != null)
group.shutdownGracefully().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException, IOException {
ProtobufEchoClient client = new ProtobufEchoClient("127.0.0.1", 9999);
try {
client.start();
for (int i = 0; i < 10; i++) {
PersonDto.Person.Builder builder = PersonDto.Person.newBuilder();
builder.setId(i);
client.send(builder.build());
}
//防止程序退出
System.in.read();
} finally {
client.close();
}
}
}
客户端处理器
public class ProtobufEchoClientInHandler extends SimpleChannelInboundHandler<PersonDto.Person> {
/**
* 客户端读取到数据
* @param ctx
* @param person
* @throws Exception
*/
@Override
public void channelRead0(ChannelHandlerContext ctx, PersonDto.Person person)
throws Exception {
System.out.println("CustomEchoClientInHandler---->name:"+person.getName()+"----->age="+person.getAge());
}
/**
* exceptionCaught()事件处理方法当出现Throwable对象才会被调用
* 即当Netty由于IO错误或者处理器在处理事件时抛出的异常时
* @param ctx
* @param cause
* @throws Exception
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
cause.printStackTrace();
ctx.close();
}
}
运行服务端和客户端,客户端发送10条消息