百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术分析 > 正文

Netty 使用 Google 的 ProtoBuf 来传输数据

liebian365 2025-02-26 12:41 1 浏览 0 评论

使用 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 的依赖



    com.google.protobuf
    protobuf-java
    3.21.5

添加 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() {
                        @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 {

        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() {
                        @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();
    }
}

相关推荐

20 个 2020 年软件开发趋势预测

企业上云已成不可逆的趋势,全面云计算时代宣告来临,微服务已成软件架构主流,Kubernetes将会变得更酷,2020年还有哪些技术趋势值得观察?一起来看!1.基础设施:条条道路通云端对于云厂商来...

目录发布!安徽这些紧缺人才急需

《安徽省5G产业急需紧缺人才目录(2020-2025)》(以下简称目录)近日正式发布。本次调研调查了216家代表企业、6家头部企业,获取了426份有效问卷,分析安徽省5G产业紧缺人才需求现状,其中产品...

AI树莓派——构建树莓派大脑(NCNN环境搭建)

前言镜像已经做好了,传到百度网盘中了(请大家及时保存,不定期删除!)...

把远程进程通讯grpc引入到Spring boot maven项目中

1、参考链接:gRPC官网:https://grpc.io/HTTP2:https://http2.github.io/...

面向数据的架构

在软件架构中,有一种模式虽鲜为人知的,但值得引起更多的关注。面向数据的架构(Data-OrientedArchitecture)由RajiveJoshi在RTI的2007年白皮书中首次提出,...

Go语言11岁了,网友:他喵的,终于确定出「泛型」了

金磊发自凹非寺量子位报道|公众号QbitAI比Python更快,比Java更简洁,还有C++没有的GC...

深度剖析数据库国产化迁移之路

作者|吴夏,腾讯云TDSQL高级工程师责编|唐小引头图|CSDN下载自东方IC出品|CSDN(ID:CSDNnews)随着国家有关部门近年来陆续出台相关政策指导文件,推动探索安...

一文掌握物体检测库TensorFlow 2.x Object Detection安装

...

团队协作-代码格式化工具clang-format

环境:clang-format:10.0.0前言统一的代码规范对于整个团队来说十分重要,通过git/svn在提交前进行统一的ClangFormat格式化,可以有效避免由于人工操作带来的代码格式问题。...

嵌入式大杂烩周记 第 9 期:nanopb

大家好,我是杂烩君。...

开源鸿蒙 OpenHarmony 3.1 Beta 版本发布:系统基础能力增强

IT之家1月2日消息,OpenAtom社区已于12月31日发布了OpenHarmony-v3.1-Beta版本。版本概述当前版本在OpenHarmony3.0LTS的基础...

零基础物联网开发,踩坑无数,得到这份宝典 | 原力计划

作者|Haor.L责编|王晓曼出品|CSDN博客笔者最近参加了校内的一场物联网开发竞赛,从零开始,踩坑无数,感觉很多时候事情都不像预料的一样发展,离开了美好的IDE,太多事情要在板子上一步...

gRPC:Google开源的基于HTTP/2和ProtoBuf的通用RPC框架

gRPC是一个高性能、通用的开源RPC框架,其由Google主要面向移动应用开发并基于HTTP/2协议标准而设计,基于ProtoBuf(ProtocolBuffers)序列化协议开发,且支持众多开发...

搜狗开源srpc:自研高性能通用RPC框架

今年7月底,搜狗公司开源了内部的工业级C++服务器引擎Workflow,一路收获业内许多认可和关注。9月15日,作为Workflow最重要的生态项目——srpc,一个基于其打造的轻量级RPC框架,也在...

WebSocket与Protobuf在现代网络通信中的应用实践

在现代网络通信中,WebSocket和Protobuf已成为构建高效、跨平台通信系统的关键技术。本文将详细介绍如何使用这两种技术来实现一个稳定且高效的网络通信系统。...

取消回复欢迎 发表评论: