程序员求职经验分享与学习资料整理平台

网站首页 > 文章精选 正文

Google Protobuf 快速入门实例(Netty)

balukai 2024-12-30 01:57:00 文章精选 10 ℃
  • Protobuf是Google发布的开源项目,全称Google Protocol Buffers,是一种轻便高效的结构化数据存储格式,可以用于结构化数据串行化,或者说序列化。它很适合做数据存储或RPC[远程过程调用remote procedure call]数据交换格式。
  • Protobuf是以message的方式来管理数据的。
  • 支持跨平台、跨语言,即[客户端和服务器端可以是不同的语言编写的](支持目前绝大多数语言,例如C++、C#、Java、python等)。
  • 高性能,高可靠性
  • 使用protobuf编译器能自动生成代码,Protobuf是将类的定义使用.proto文件进行描述。
  • 参考文档:https://developers.google.com/protocol-buffers/docs/proto语言指南

实例1:客户端可以发送一个Student PoJo对象到服务器(通过Protobuf编码);服务端能接收Student PoJo对象,并显示信息(通过Protobuf解码)

1、Student.proto代码:

syntax = "proto3"; //版本
option java_outer_classname = "StudentPOJO"; //生成的java类名
//使用message管理数据,会在StudentPOJO类中生成一个内部类Student
message Student {
  int32 id = 1; //对应Student类中的属性int id,1:表示属性序号
  string name = 2; //对应Student类中的属性String name,2:表示属性序号
}

2、通过Student.proto生成StudentPOJO类:



3、服务器端代码:

package com.netty.codec;
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;

public class NettyServer {
    public static void main(String[] args) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            //添加protobuf解码器,需指定对哪种对象解码
                            pipeline.addLast(new ProtobufDecoder(StudentPOJO.Student.getDefaultInstance()));
                            //添加业务处理器
                            //pipeline.addLast(new NettyServerHandler());
                            pipeline.addLast(new NettyServerSimpleHandler());
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind(7000).sync();
            System.out.println("Netty服务器启动...");
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

package com.netty.codec;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

public class NettyServerSimpleHandler extends SimpleChannelInboundHandler<StudentPOJO.Student> {
    /**
     * 读取数据
     * @param ctx
     * @param student
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, StudentPOJO.Student student) throws Exception {
        System.out.println("客户端发送的数据:{id: "+ student.getId() +", name: "+ student.getName() +"}");
        System.out.println("客户端地址:"+ ctx.channel().remoteAddress());
    }
    /**
     * 读取数据完毕后触发
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.channel().writeAndFlush(Unpooled.copiedBuffer("hello,客户端~", CharsetUtil.UTF_8));
    }
    /**
     * 发生异常时的处理
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}

4、客户端代码:

package com.netty.codec;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
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.ProtobufEncoder;

public class NettyClient {
    public static void main(String[] args) throws Exception {
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            //添加protobuf编码器
                            pipeline.addLast(new ProtobufEncoder());
                            //添加业务数据处理器
                            pipeline.addLast(new NettyClientHandler());
                        }
                    });
            ChannelFuture future = bootstrap.connect("127.0.0.1", 7000).sync();
            future.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
}

package com.netty.codec;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

public class NettyClientHandler extends ChannelInboundHandlerAdapter {
    /**
     * 当通道准备就绪(激活)时触发
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //发送Student对象给服务器端
        StudentPOJO.Student student = StudentPOJO.Student.newBuilder().setId(10001).setName("张三").build();
        ctx.channel().writeAndFlush(student);
    }
    /**
     * 读取数据
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buffer = (ByteBuf) msg;
        System.out.println("服务器端回复的数据:"+ buffer.toString(CharsetUtil.UTF_8));
        System.out.println("服务器端地址:"+ ctx.channel().remoteAddress());
    }
    /**
     * 发生异常时的处理
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}

实例2:实现传输多种类型数据;客户端可以随机发送Student PoJo/Worker PoJo对象到服务器(通过Protobuf编码);服务端能接收Student PoJo/Worker PoJo对象(需要判断是哪种类型),并显示信息(通过Protobuf解码)

1、Student.proto代码:

syntax = "proto3"; //版本
option optimize_for = SPEED; //加速解析
option java_package = "com.netty.codec2"; //指定java文件生成到哪个包下
option java_outer_classname = "CustomData"; //生成的Java类名
//protobuf可以使用message管理其他message
message Info {
  //定义一个枚举
  enum DataType {
      StudentType = 0;
      SubjectType = 1;
  }
  //用DataType类表示传的是哪一个枚举类型
  DataType type = 1;
  //表示每次枚举类型最多只能出现其中的一个,节省空间
  oneof dataBody {
      Student student = 2;
      Subject subject = 3;
  }
}
//使用message管理数据,会在CustomData类中生成一个内部类Student
message Student {
  int32 id = 1;
  string name = 2;
}
message Subject {
  string name = 1;
  int32 code = 2;
}

通过Student.proto生成CustomData类,然后将CustomData类拷贝到com.netty.codec2包下。

2、服务器端代码:

package com.netty.codec2;
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;

public class NettyServer {
    public static void main(String[] args) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            //添加protobuf解码器,需指定对哪种对象解码
                            pipeline.addLast(new ProtobufDecoder(CustomData.Info.getDefaultInstance()));
                            //添加业务处理器
                            pipeline.addLast(new NettyServerHandler());
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind(7000).sync();
            System.out.println("Netty服务器启动...");
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

package com.netty.codec2;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

public class NettyServerHandler extends SimpleChannelInboundHandler<CustomData.Info> {
    /**
     * 读取数据
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, CustomData.Info msg) throws Exception {
        CustomData.Info.DataType type = msg.getType();
        if (type == CustomData.Info.DataType.StudentType) {
            CustomData.Student student = msg.getStudent();
            System.out.println("客户端发送的学生信息:{id: "+ student.getId() +", name: "+ student.getName() +"}");
        } else if (type == CustomData.Info.DataType.SubjectType) {
            CustomData.Subject subject = msg.getSubject();
            System.out.println("客户端发送的科目信息:{name: "+ subject.getName() +", code: "+ subject.getCode() +"}");
        } else {
            System.out.println("传输的数据类型不合法...");
        }
        System.out.println("客户端地址:"+ ctx.channel().remoteAddress());
    }
    /**
     * 读取数据完毕后触发
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.channel().writeAndFlush(Unpooled.copiedBuffer("hello,客户端~", CharsetUtil.UTF_8));
    }
    /**
     * 发生异常时的处理
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}

3、客户端代码:

package com.netty.codec2;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
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.ProtobufEncoder;

public class NettyClient {
    public static void main(String[] args) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            //添加protobuf编码器
                            pipeline.addLast(new ProtobufEncoder());
                            //添加业务数据处理器
                            pipeline.addLast(new NettyClientHandler());
                        }
                    });
            ChannelFuture future = bootstrap.connect("127.0.0.1", 7000).sync();
            future.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
}

package com.netty.codec2;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import java.util.Random;

public class NettyClientHandler extends ChannelInboundHandlerAdapter {
    /**
     * 当通道准备就绪(激活)时触发
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //随机发送Student或Subject对象给服务器端
        int random = new Random().nextInt(3);
        CustomData.Info data = null;
        if (0 == random) { //发送Student对象
            data = CustomData.Info.newBuilder().setType(CustomData.Info.DataType.StudentType).setStudent(CustomData.Student.newBuilder().setId(10002).setName("王老五").build()).build();
        } else {
            data = CustomData.Info.newBuilder().setType(CustomData.Info.DataType.SubjectType).setSubject(CustomData.Subject.newBuilder().setName("语文").setCode(1).build()).build();
        }
        ctx.channel().writeAndFlush(data);
    }
    /**
     * 读取数据
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buffer = (ByteBuf) msg;
        System.out.println("服务器端回复的数据:"+ buffer.toString(CharsetUtil.UTF_8));
        System.out.println("服务器端地址:"+ ctx.channel().remoteAddress());
    }
    /**
     * 发生异常时的处理
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}

Tags:

最近发表
标签列表