Netty学习之路(八)-Google Protobuf编码

Protobuf是一个灵活,高效,结构化的数据序列化框架,相比于XML等传统的序列化工具,它更小,更快,更简单。Protobuf支持数据结构化一次可以到处使用,甚至可以跨语言使用,通过代码生成工具可以自动生成不同语言版本的源代码,甚至可以在使用不同版本的数据结构进程间进行数据传递,实现数据结构的前向兼容。

Protobuf入门

首先下载Protobuf的最新Windows版本:地址,下载底部的protoc-3.6.1-win32.zip。
解压后得到protoc.exe工具,此工具根据.proto文件生成代码。详细protobuf java使用请看这里,根据教程编写如下.proto文件:

syntax = "proto3";

message book_data {
    int64 id = 1;
    string name =2;
    string dataTime = 3;
    string type = 4;
}

再通过protoc -I=src/com/ph/proto/resource --java_out=src/com/ph/proto/java src/com/ph/proto/resource/book_data.proto生成java代码。导入jar包

在Netty中使用Protobuf

首先需要用protoc.exe生成对应的BookData java代码。

服务端

package com.ph.Netty;

import com.ph.proto.java.BookData;
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.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;

/**
 * Create by PH on 2018/11/9
 */
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(new ProtobufVarint32FrameDecoder());
                            //解码器,参数是com.google.protobuf.MessageLite,告诉ProtobufDecoder需要解码的目标类型
                            arg0.pipeline().addLast(new ProtobufDecoder(BookData.book_data.getDefaultInstance()));
                            arg0.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
                            arg0.pipeline().addLast(new ProtobufEncoder());
                            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 {
        BookData.book_data req = (BookData.book_data)msg;
        System.out.println("Server receive : " + req.toString());
        BookData.book_data.Builder builder = BookData.book_data.newBuilder();
        builder.setId(req.getId());
        builder.setName("Netty");
        builder.setDataTime("2018-11-9 14:25:44");
        builder.setType("buy succeed");
        ctx.writeAndFlush(builder.build());
    }

    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //将消息发送队列中的消息写入到SocketChannel中发送给对方
        ctx.flush();
    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        //当发生异常时释放资源
        ctx.close();
    }
}

客户端

package com.ph.Netty;

import com.ph.proto.java.BookData;
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.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;

/**
 * Create by PH on 2018/11/9
 */
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(new ProtobufVarint32FrameDecoder());
                            //解码器,参数是com.google.protobuf.MessageLite,告诉ProtobufDecoder需要解码的目标类型
                            ch.pipeline().addLast(new ProtobufDecoder(BookData.book_data.getDefaultInstance()));
                            ch.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
                            ch.pipeline().addLast(new ProtobufEncoder());
                            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) {
        for (int i=0;i<sendNumber;i++) {
            BookData.book_data.Builder builder = BookData.book_data.newBuilder();
            builder.setId(i);
            builder.setName("Netty");
            builder.setDataTime("2018-11-9 14:25:44");
            builder.setType("buy book");
            ctx.write(builder.build());
        }
        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();
    }
}

Protobuf的使用注意事项

ProtobufDecoder仅仅负责解码,它不支持读半包。因此,在ProtobufDecoder前面,一定要有能够处理半包的解码器,有以下三种方式可以选择:

  1. 使用Netty提供的ProtobufVarint32FrameDecoder,它可以处理半包消息
  2. 继承Netty提供的通用半包解码器LengthFieldBasedFrameDecoder
  3. 继承ByteToMessageDecoder类,自己处理半包消息

猜你喜欢

转载自blog.csdn.net/PH15045125/article/details/83899962