Google Protobuf 快速入门实例(Netty)
ztj100 2024-12-14 16:12 45 浏览 0 评论
- 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();
}
}
相关推荐
- Docker安全开放远程访问连接权限(docker 远程授权访问)
-
1、Docker完全开放远程访问Docker服务完全开放对外访问权限操作如下:#开启端口命令(--permanent永久生效,没有此参数重启后失效)firewall-cmd--zone=pu...
- SpringCloud系列——4OpenFeign简介及应用
-
学习目标什么是OpenFeign以及它的作用RPC到底怎么理解OpenFeign的应用第1章OpenFeign简介在前面的内容中,我们分析了基于RestTemplate实现http远程通信的方法。并...
- Spring Boot集成qwen:0.5b实现对话功能
-
1.什么是qwen:0.5b?模型介绍:Qwen1.5是阿里云推出的一系列大型语言模型。Qwen是阿里云推出的一系列基于Transformer的大型语言模型,在大量数据(包括网页文本、书籍、代码等)...
- JDK从8升级到21的问题集(jdk8升级到11)
-
一、背景与挑战1.升级动因oOracle长期支持策略o现代特性需求:协程、模式匹配、ZGC等o安全性与性能的需求oAI新技术引入的版本要求...
- 大白话详解Spring Cloud服务降级与熔断
-
1.Hystrix断路器概述1.1分布式系统面临的问题复杂分布式体系结构中的应用程序有数十个依赖关系,每个依赖关系在某些时候将不可避免地失败。这就造成有可能会发生...
- 面试突击43:lock、tryLock、lockInterruptibly有什么区别?
-
在Lock接口中,获取锁的方法有4个:lock()、tryLock()、tryLock(long,TimeUnit)、lockInterruptibly(),为什么需要这么多方法?这些方法都有...
- 了解网络编程 TCP/IP 协议与UDP 协议
-
因为iP地址比较难记忆,很多情况下可以使用域名代替iP地址。1.TCP/IP协议与UDP协议通过IP地址与端口号确定计算机在网络中的位置后,接下来考虑通讯的问题:因为不同计算机的软硬件平台...
- Semaphore与Exchanger的区别(semaphore和signal)
-
Semaphore和Exchanger是Java并发编程中两个常用的同步工具类,它们都可以用于协调多个线程之间的执行顺序和状态,但它们的作用和使用方式有所不同:Semaphore类表示一个...
- Java教程:什么是分布式任务调度?怎样实现任务调度?
-
通常任务调度的程序是集成在应用中的,比如:优惠卷服务中包括了定时发放优惠卷的的调度程序,结算服务中包括了定期生成报表的任务调度程序...
- java多线程—Runnable、Thread、Callable区别
-
多线程编程优点:进程之间不能共享内存,但线程之间共享内存非常容易。系统创建线程所分配的资源相对创建进程而言,代价非常小。Java中实现多线程有3种方法:继承Thread类实现Runnable...
- 工厂模式详解(工厂模式是啥意思)
-
工厂模式详解简单工厂简单工厂模式(SimpleFactoryPattern)是指由一个工厂对象决定创建出哪一种产品类的实例。简单工厂适用于工厂类负责创建的对象较少的场景,且客户端只需要传入工厂类的...
- 我们程序员眼中的母亲节(你眼中的程序员是什么样子的?程序员的薪酬如何?)
-
导语:对于我们成人来说,尤其是漂泊在外的程序员,陪伴父母的时间太少了。每逢佳节倍思亲,我们流浪外在的游子应该深有感触。母亲,是世界上最伟大的人,她承载着对我们的爱,更是负担和压力。我们作为子女,只会嫌...
- 死锁的 4 种排查工具(死锁检测方法要解决两个问题)
-
死锁(DeadLock)指的是两个或两个以上的运算单元(进程、线程或协程),都在等待对方停止执行,以取得系统资源,但是没有一方提前退出,就称为死锁。死锁示例接下来,我们先来演示一下Java中最简...
- 1. 工厂模式详解(工厂模式示例)
-
我们的项目代码也是由简而繁一步一步迭代而来的,但对于调用者来说却是越来越简单化。简单工厂模式简单工厂模式(SimpleFactoryPattern)是指由一个工厂对象决定创建出哪一种产品类的实例。...
- Jmeter(二十):jmeter对图片验证码的处理
-
jmeter对图片验证码的处理在web端的登录接口经常会有图片验证码的输入,而且每次登录时图片验证码都是随机的;当通过jmeter做接口登录的时候要对图片验证码进行识别出图片中的字段,然后再登录接口中...
你 发表评论:
欢迎- 一周热门
- 最近发表
-
- Docker安全开放远程访问连接权限(docker 远程授权访问)
- SpringCloud系列——4OpenFeign简介及应用
- Spring Boot集成qwen:0.5b实现对话功能
- JDK从8升级到21的问题集(jdk8升级到11)
- 大白话详解Spring Cloud服务降级与熔断
- 面试突击43:lock、tryLock、lockInterruptibly有什么区别?
- 了解网络编程 TCP/IP 协议与UDP 协议
- Semaphore与Exchanger的区别(semaphore和signal)
- Java教程:什么是分布式任务调度?怎样实现任务调度?
- java多线程—Runnable、Thread、Callable区别
- 标签列表
-
- idea eval reset (50)
- vue dispatch (70)
- update canceled (42)
- order by asc (53)
- spring gateway (67)
- 简单代码编程 贪吃蛇 (40)
- transforms.resize (33)
- redisson trylock (35)
- 卸载node (35)
- np.reshape (33)
- torch.arange (34)
- npm 源 (35)
- vue3 deep (35)
- win10 ssh (35)
- vue foreach (34)
- idea设置编码为utf8 (35)
- vue 数组添加元素 (34)
- std find (34)
- tablefield注解用途 (35)
- python str转json (34)
- java websocket客户端 (34)
- tensor.view (34)
- java jackson (34)
- vmware17pro最新密钥 (34)
- mysql单表最大数据量 (35)