Netty 使用 Google 的 ProtoBuf 来传输数据

使用 Google 的 ProtoBuf 来传输数据

ProtoBuf 是 google 的一个文件传输的协议。与平台语言无关。

编写 proto 文件 (用来生成 Java 文件 pojo 的)

syntax = "proto3"; // 表示协议的版本
option java_outer_classname = "StudentPojo"; // 类名同时也是文件名字

// ProtoBuf 是以 message 来管理数据的
message Student {// 会在 java_outer_classname 的类中生成的内部类,他是真正的 传输的 pojo 对象
  int32 id = 1; //  int32 => proto 类型,对应 Java 的 int 类型。(Student 内有一个属性 id,类型为 int32, 1 代表属性序号,并不是值)
  string name = 2;
}

生成 Java 的实体类 protoc.exe --java_out=. Student.proto,执行这个命令以后就会生成一个指定的 Java 文件。然后把这个文件 copy 到自己的项目的工作路径。

使用 Netty 来实现 ProtoBuf 的数据传输

引入 maven 的依赖

<!-- protoBuf -->
<dependency>
    <groupId>com.google.protobuf</groupId>
    <artifactId>protobuf-java</artifactId>
    <version>3.21.5</version>
</dependency>

添加 ProtoBuf 处理器到 server 和 client

pipeline.addLast(new ProtobufEncoder()); // ProtoBuf 的编码器
pipeline.addLast(new ProtobufDecoder(StudentPojo.Student.getDefaultInstance())); // ProtoBuf 的解码器

发送消息进行通讯

StudentPojo.Student student = StudentPojo.Student.newBuilder().setId(4).setName("孙悟空").build();
log.info("发送的数据 => {}", student);
ctx.writeAndFlush(student);

这样就是 netty 使用 ProtoBuf 的关键代码。

完整代码

服务端

package com.netty.codec;

import com.utils.LoggerUtils;
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 org.slf4j.Logger;

public class GoogleProtobufCodecServer {

    /**
     * 初始化服务
     */
    public void init() throws InterruptedException {
        EventLoopGroup boosGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            ChannelFuture channelFuture = serverBootstrap
                    .group(boosGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            // 添加处理器
                            ChannelPipeline pipeline = ch.pipeline();
                            // ProtoBuf 编解码器
                            pipeline.addLast(new ProtobufEncoder());
                            pipeline.addLast(new ProtobufDecoder(StudentPojo.Student.getDefaultInstance()));
                            // 自定义处理器
                            pipeline.addLast(new ProtoBufHandler());
                        }
                    })
                    // 绑定端口
                    .bind(6666).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            boosGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

    /**
     * 自定义处理器
     *
     * @author L
     */
    private static class ProtoBufHandler extends SimpleChannelInboundHandler<StudentPojo.Student> {

        Logger log = LoggerUtils.getLogger(ProtoBufHandler.class);

        /**
         * 通道初始化完成以后
         */
        @Override
        public void channelActive(ChannelHandlerContext ctx) {
            StudentPojo.Student student = StudentPojo.Student.newBuilder().setId(4).setName("孙悟空").build();
            log.info("发送的数据 => {}", student);
            ctx.writeAndFlush(student);
        }

        /**
         * 接收到消息以后
         *
         * @param ctx the {@link ChannelHandlerContext} which this {@link SimpleChannelInboundHandler}
         *            belongs to
         * @param msg the message to handle
         */
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, StudentPojo.Student msg) {
            log.info("客户端发送的数据 => id={},name={}", msg.getId(), msg.getId());
        }
    }

    /**
     * 代码允许
     */
    public static void main(String[] args) throws InterruptedException {
        new GoogleProtobufCodecServer().init();
    }
}

客户端

package com.netty.codec;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GoogleProtobufCodecClient {

    Logger log = LoggerFactory.getLogger(GoogleProtobufCodecClient.class);

    public void init() throws InterruptedException {
        EventLoopGroup clientGroup = new NioEventLoopGroup();
        try {
            // 创建一个 bootstrap 而不是 serverBootstrap
            Bootstrap bootstrap = new Bootstrap();
            // 设置相关管参数
            bootstrap
                    // 设置线程组
                    .group(clientGroup)
                    // 设置客户端通道的实现类(反射)
                    .channel(NioSocketChannel.class)
                    // 设置处理器
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel nioSocketChannel) {
                            // 添加自己的 handler 处理器
                            ChannelPipeline pipeline = nioSocketChannel.pipeline();
                            pipeline.addLast(new ProtobufEncoder());
                            pipeline.addLast(new ProtobufDecoder(StudentPojo.Student.getDefaultInstance()));
                            pipeline.addLast(new ChannelInboundHandlerAdapter() {
                                @Override
                                public void channelRead(ChannelHandlerContext ctx, Object msg) {
                                    log.info("服务端消息 => {}", msg);
                                }
                            });
                        }
                    });
            log.info("客户端准备 OK");
            // 启动客户端去链接服务端,涉及到 netty 的异步模型
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 6666).sync();
            // 给通道关闭进行监听
            channelFuture.channel().closeFuture().sync();
        } finally {
            clientGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new GoogleProtobufCodecClient().init();
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
93个netty高并发全面的教学视频下载,每个视频在400-700M,一到两个小时时长的视频,无机器码和解压密码,下载下来的就是MP4格式视频。点击即可观看学习。下载txt文档,里面有永久分享的连接。包括01_学习的要义;02_Netty宏观理解;03_Netty课程大纲深度解读;04_项目环境搭建与Gradle配置;05_Netty执行流程分析与重要组件介绍;06_Netty回调与Channel执行流程分析;07_Netty的Socket编程详解;08_Netty多客户端连接与通信,09_Netty读写检测机制与长连接要素,10_Netty对WebSocket的支援;11_Netty实现服务器端与客户端的长连接通信;12_Google Protobuf详解;13_定义Protobuf文件及消息详解;14_Protobuf完整实例详解;15_Protobuf集成Netty与多协议消息递;16_Protobuf多协议消息支援与工程最佳实践;17_Protobuf使用最佳实践与Apache Thrift介绍;18_Apache Thrift应用详解与实例剖析;19_Apache Thrift原理与架构解析;20_通过Apache Thrift实现Java与Python的RPC调用;21_gRPC深入详解 ;22_gRPC实践 ;23_Gradle Wrapper在Gradle项目构建中的最佳实践;24_gRPC整合Gradle与代码生成············82_Netty引用计数原子更新揭秘与AtomicIntegerFieldUpdater深度剖析;83_AtomicIntegerFieldUpdater实例演练与volatile关键字分析;84_Netty引用计数注意事项与内存泄露检测方式;85_Netty编解码器剖析与入站出站处理器详解;86_Netty自定义编解码器与TCP粘包拆包问题;87_Netty编解码器执行流程深入分析;88_ReplayingDecoder源码分析与特性解读;89_Netty常见且重要编解码器详解;90_TCP粘包与拆包实例演示及分析;91_Netty自定义协议与TCP粘包拆包问题解决之道;92_精通并发与Netty课程总结与展望

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值