1. 程式人生 > >Netty學習之路(八)-Google Protobuf編碼

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類,自己處理半包訊息