Google Protobuf 快速入门实例(Netty)
bigegpt 2024-11-24 12:00 3 浏览
- 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();
}
}
相关推荐
- 悠悠万事,吃饭为大(悠悠万事吃饭为大,什么意思)
-
新媒体编辑:杜岷赵蕾初审:程秀娟审核:汤小俊审签:周星...
- 高铁扒门事件升级版!婚宴上‘冲喜’老人团:我们抢的是社会资源
-
凌晨两点改方案时,突然收到婚庆团队发来的视频——胶东某酒店宴会厅,三个穿大红棉袄的中年妇女跟敢死队似的往前冲,眼瞅着就要扑到新娘的高额钻石项链上。要不是门口小伙及时阻拦,这婚礼造型团队熬了三个月的方案...
- 微服务架构实战:商家管理后台与sso设计,SSO客户端设计
-
SSO客户端设计下面通过模块merchant-security对SSO客户端安全认证部分的实现进行封装,以便各个接入SSO的客户端应用进行引用。安全认证的项目管理配置SSO客户端安全认证的项目管理使...
- 还在为 Spring Boot 配置类加载机制困惑?一文为你彻底解惑
-
在当今微服务架构盛行、项目复杂度不断攀升的开发环境下,SpringBoot作为Java后端开发的主流框架,无疑是我们手中的得力武器。然而,当我们在享受其自动配置带来的便捷时,是否曾被配置类加载...
- Seata源码—6.Seata AT模式的数据源代理二
-
大纲1.Seata的Resource资源接口源码2.Seata数据源连接池代理的实现源码3.Client向Server发起注册RM的源码4.Client向Server注册RM时的交互源码5.数据源连接...
- 30分钟了解K8S(30分钟了解微积分)
-
微服务演进方向o面向分布式设计(Distribution):容器、微服务、API驱动的开发;o面向配置设计(Configuration):一个镜像,多个环境配置;o面向韧性设计(Resista...
- SpringBoot条件化配置(@Conditional)全面解析与实战指南
-
一、条件化配置基础概念1.1什么是条件化配置条件化配置是Spring框架提供的一种基于特定条件来决定是否注册Bean或加载配置的机制。在SpringBoot中,这一机制通过@Conditional...
- 一招解决所有依赖冲突(克服依赖)
-
背景介绍最近遇到了这样一个问题,我们有一个jar包common-tool,作为基础工具包,被各个项目在引用。突然某一天发现日志很多报错。一看是NoSuchMethodError,意思是Dis...
- 你读过Mybatis的源码?说说它用到了几种设计模式
-
学习设计模式时,很多人都有类似的困扰——明明概念背得滚瓜烂熟,一到写代码就完全想不起来怎么用。就像学了一堆游泳技巧,却从没下过水实践,很难真正掌握。其实理解一个知识点,就像看立体模型,单角度观察总...
- golang对接阿里云私有Bucket上传图片、授权访问图片
-
1、为什么要设置私有bucket公共读写:互联网上任何用户都可以对该Bucket内的文件进行访问,并且向该Bucket写入数据。这有可能造成您数据的外泄以及费用激增,若被人恶意写入违法信息还可...
- spring中的资源的加载(spring加载原理)
-
最近在网上看到有人问@ContextConfiguration("classpath:/bean.xml")中除了classpath这种还有其他的写法么,看他的意思是想从本地文件...
- Android资源使用(android资源文件)
-
Android资源管理机制在Android的开发中,需要使用到各式各样的资源,这些资源往往是一些静态资源,比如位图,颜色,布局定义,用户界面使用到的字符串,动画等。这些资源统统放在项目的res/独立子...
- 如何深度理解mybatis?(如何深度理解康乐服务质量管理的5个维度)
-
深度自定义mybatis回顾mybatis的操作的核心步骤编写核心类SqlSessionFacotryBuild进行解析配置文件深度分析解析SqlSessionFacotryBuild干的核心工作编写...
- @Autowired与@Resource原理知识点详解
-
springIOCAOP的不多做赘述了,说下IOC:SpringIOC解决的是对象管理和对象依赖的问题,IOC容器可以理解为一个对象工厂,我们都把该对象交给工厂,工厂管理这些对象的创建以及依赖关系...
- java的redis连接工具篇(java redis client)
-
在Java里,有不少用于连接Redis的工具,下面为你介绍一些主流的工具及其特点:JedisJedis是Redis官方推荐的Java连接工具,它提供了全面的Redis命令支持,且...
- 一周热门
- 最近发表
- 标签列表
-
- mybatiscollection (79)
- mqtt服务器 (88)
- keyerror (78)
- c#map (65)
- resize函数 (64)
- xftp6 (83)
- bt搜索 (75)
- c#var (76)
- mybatis大于等于 (64)
- xcode-select (66)
- mysql授权 (74)
- 下载测试 (70)
- linuxlink (65)
- pythonwget (67)
- androidinclude (65)
- logstashinput (65)
- hadoop端口 (65)
- vue阻止冒泡 (67)
- oracle时间戳转换日期 (64)
- jquery跨域 (68)
- php写入文件 (73)
- kafkatools (66)
- mysql导出数据库 (66)
- jquery鼠标移入移出 (71)
- 取小数点后两位的函数 (73)