springboot整合gprc 传输对象
2019独角兽企业重金招聘Python工程师标准>>>
一,grpc简介:
GRPC是google开源的一个高性能、跨语言的RPC框架,基于HTTP2协议,基于protobuf 3.x,基于Netty 4.x +。GRPC与thrift、avro-rpc等其实在总体原理上并没有太大的区别,简而言之GRPC并没有太多突破性的创新。
对于开发者而言:
1)需要使用protobuf定义接口,即.proto文件
2)然后使用compile工具生成特定语言的执行代码,比如JAVA、C/C++、Python等。类似于thrift,为了解决跨语言问题。
3)启动一个Server端,server端通过侦听指定的port,来等待Client链接请求,通常使用Netty来构建,GRPC内置了Netty的支持。
4)启动一个或者多个Client端,Client也是基于Netty,Client通过与Server建立TCP常链接,并发送请求;Request与Response均被封装成HTTP2的stream Frame,通过Netty Channel进行交互。
二,proto3:
Protocol Buffers是一个跨语言、跨平台的具有可扩展机制的序列化数据工具。也就是说,我在ubuntu下用python语言序列化一个对象,并使用http协议传输到使用java语言的android客户端,java使用对用的代码工具进行反序列化,也可以得到对应的对象。听起来好像跟json没有多大区别。。。其实区别挺多的。
Google说protobuf是smaller,faster,simpler,我们使用google规定的proto协议定义语言,之后使用proto的工具对代码进行“编译”,生成对应的各个平台的源代码,我们可以使用这些源代码进行工作。
Proto2与proto3:
Proto2和proto3有些区别,包括proto语言的规范,以及生成的代码,proto3更好用,更简便,所以我们直接存proto3开始。
三,Grpc Spring Boot Starter
grpc对于springboot封装的Starter,
Grpc Spring Boot Starter地址:https://github.com/yidongnan/grpc-spring-boot-starter
1,用法:
a, 使用proto3生成java文件:
[java] view plain copy
- <properties>
- <jackson.version>2.8.3</jackson.version>
- <grpc.version>1.6.1</grpc.version>
- <os.plugin.version>1.5.0.Final</os.plugin.version>
- <protobuf.plugin.version>0.5.0</protobuf.plugin.version>
- <protoc.version>3.3.0</protoc.version>
- <grpc.netty.version>4.1.14.Final</grpc.netty.version>
- </properties>
- <dependencies>
- <dependency>
- <groupId>io.grpc</groupId>
- <artifactId>grpc-netty</artifactId>
- <version>${grpc.version}</version>
- </dependency>
- <dependency>
- <groupId>io.grpc</groupId>
- <artifactId>grpc-protobuf</artifactId>
- <version>${grpc.version}</version>
- </dependency>
- <dependency>
- <groupId>io.grpc</groupId>
- <artifactId>grpc-stub</artifactId>
- <version>${grpc.version}</version>
- </dependency>
- <dependency>
- <groupId>io.netty</groupId>
- <artifactId>netty-common</artifactId>
- <version>${grpc.netty.version}</version>
- </dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-annotations</artifactId>
- <version>${jackson.version}</version>
- </dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-core</artifactId>
- <version>${jackson.version}</version>
- </dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-databind</artifactId>
- <version>${jackson.version}</version>
- </dependency>
- </dependencies>
- <build>
- <extensions>
- <extension>
- <groupId>kr.motd.maven</groupId>
- <artifactId>os-maven-plugin</artifactId>
- <version>${os.plugin.version}</version>
- </extension>
- </extensions>
- <plugins>
- <plugin>
- <groupId>org.xolstice.maven.plugins</groupId>
- <artifactId>protobuf-maven-plugin</artifactId>
- <version>${protobuf.plugin.version}</version>
- <configuration>
- <protocArtifact>com.google.protobuf:protoc:${protoc.version}:exe:${os.detected.classifier}</protocArtifact>
- <pluginId>grpc-java</pluginId>
- <pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact>
- </configuration>
- <executions>
- <execution>
- <goals>
- <goal>compile</goal>
- <goal>compile-custom</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
注意版本号,如果包版本不一致可能会有classnotFound的error
b,编写proto3文件,
[java] view plain copy
- syntax = "proto3";
- option java_multiple_files = true;
- option java_package = "com.aiccms.device.grpc.lib";
- option java_outer_classname = "DeviceFixProto";
- option objc_class_prefix = "HLW";
- package device;
- // The device service definition.
- service DeviceFixService {
- // Sends a message
- rpc insertDeviceFix (deviceFix) returns (booleanReply){}
- rpc updateDeviceFix (deviceFix) returns (booleanReply){}
- rpc searchDeviceFix (conditionsRequest) returns (deviceFix){}
- rpc deleteDeviceFix (conditionsRequest) returns (booleanReply){}
- }
- // The request message .
- message conditionsRequest {
- string id = 1;
- }
- message deviceFix {
- string id=1;
- string serialNum=2;
- string userNum=3;
- int32 status=4;
- int32 type=5;
- string address=6;
- string createtime=7;
- string updatetime=8;
- }
- // The response message
- message booleanReply {
- bool reply = 1;
- }
- // The response message
- message objectReply {
- bool reply = 1;
- }
编写proto3文件,开头syntax中要指定为proto3版本。其他语法这里不做详细介绍。
c,使用mvn命令 protobuf:compile 和protobuf:compile-custom命令编译生成java文件
生成之后的文件在target目录中
注意:proto目录与java目录同级
d,以上这些都在一个公共的工程当中,因为这些类不管是客户端和服务端都要使用。
e,编写grpc服务端,首先添加maven依赖
[html] view plain copy
- <grpc.stater.version>1.3.0-RELEASE</grpc.stater.version>
- <dependency>
- <groupId>net.devh</groupId>
- <artifactId>grpc-server-spring-boot-starter</artifactId>
- <version>${grpc.stater.version}</version>
- </dependency>
f,服务端代码
[html] view plain copy
- /**
- * User: hmemb
- * Email: 949530857@qq.com
- * Date: 2018/1/9
- */
- @Slf4j
- @GrpcService(DeviceFixServiceGrpc.class)
- public class deviceGrpcService extends DeviceFixServiceGrpc.DeviceFixServiceImplBase{
- @Autowired
- private IDevicesFixService deviceService;
- @Override
- public void insertDeviceFix(deviceFix request, StreamObserver<booleanReply> responseObserver) {
- DevicesFix deviceFix = DevicesFix.builder().id(request.getId())
- .serialNum(request.getSerialNum())
- .address(request.getAddress())
- .createtime(DateUtil.toDate(request.getCreatetime(), DatePattern.TIMESTAMP))
- .updatetime(DateUtil.toDate(request.getUpdatetime(), DatePattern.TIMESTAMP))
- .userNum(request.getUserNum())
- .status(request.getStatus())
- .type(request.getType())
- .build();
- log.info(deviceFix.toString());
- boolean replyTag = deviceService.insert(deviceFix);
- booleanReply reply = booleanReply.newBuilder().setReply(replyTag).build();
- responseObserver.onNext(reply);
- responseObserver.onCompleted();
- }
g,在配置文件中添加配置信息
[html] view plain copy
- #grpc server config
- spring.application.name: device-grpc-server
- grpc.server.port:7052
h,编写客户端代码:引入maven依赖
[html] view plain copy
- <grpc.stater.version>1.3.0-RELEASE</grpc.stater.version
[html] view plain copy
- <dependency>
- <groupId>net.devh</groupId>
- <artifactId>grpc-client-spring-boot-starter</artifactId>
- <version>${grpc.stater.version}</version>
- </dependency>
i,编写gprc接口实现,注解@grpcClient 填写grpc接口名称
[java] view plain copy
- /**
- * User: hmemb
- * Email: 949530857@qq.com
- * Date: 2018/01/19
- */
- @Service
- @Slf4j
- public class DeviceGrpcService {
- @GrpcClient("device-grpc-server")
- private Channel serverChannel;
- public String insertDeviceFix( ){
- DeviceFixServiceGrpc.DeviceFixServiceBlockingStub stub = DeviceFixServiceGrpc.newBlockingStub(serverChannel);
- booleanReply response = stub.insertDeviceFix(
- deviceFix.newBuilder()
- .setId("UUID-O1")
- .setSerialNum("AUCCMA-01")
- .setAddress("SHENZHEN")
- .setCreatetime(DateUtil.toString(new Date(), DatePattern.TIMESTAMP))
- .setUpdatetime(DateUtil.toString(new Date(), DatePattern.TIMESTAMP))
- .setStatus(1)
- .setType(1)
- .build());
- log.info("grpc消费者收到:--》"+response.getReply());
- if(response.getReply()){
- return "success";
- }else{
- return "fail";
- }
- }
- }
j,配置文件中加入接口的服务端地址,grpc.client.[服务器规定的接口名称].post/host
[html] view plain copy
- grpc.client.device-grpc-server.host:127.0.0.1
- grpc.client.device-grpc-server.port:7052
k,封装成http rest接口测试
[java] view plain copy
- /**
- * @Author:Hmemb
- * @Description:
- * @Date:Created in 18:24 2018/1/18
- */
- @RestController
- @Api(value = "Testcontroller", description = "测试swagger")
- public class Testcontroller {
- @Autowired
- private DeviceGrpcService deviceGrpcService;
- @RequestMapping("/testInsertDeviceFix")
- @ApiOperation(value = "test", httpMethod = "GET", notes = "测试grpc插入")
- public String printMessage3(@RequestParam(defaultValue = "Hmemb") String name) {
- return deviceGrpcService.insertDeviceFix();
- }
- @RequestMapping("/TEST1")
- @ApiOperation(value = "test", httpMethod = "GET", notes = "测试1")
- public String printMessage(@RequestParam(defaultValue = "Michael") String name) {
- return name;
- }
- }
l,接口测试结果
我只实现了proto中的一个接口,其他接口同理。
转载于:https://my.oschina.net/xiaominmin/blog/1801385
springboot整合gprc 传输对象相关推荐
- SpringBoot整合——阿里云对象存储(OSS)
SpringBoot整合--阿里云对象存储 1 OSS介绍 在开发应用的过程中,我们经常会有用户需要实名认证之后才能访问的需求. 用户认证需要上传证件图片.首页轮播也需要上传图片,因此我们要做文件服务 ...
- springboot整合阿里云对象存储oss
知识梳理: 今天要学的知识很实用,一个合格的项目里面肯定会用到这个技术,那就是文件上传,文件上传可以帮我们上传头像.excel表格.等,用过文件上传的小伙伴都是文件上传到哪里去呢?本人第一次上传文件是 ...
- SpringBoot整合Redis存储对象数据是乱码数据解决方法
将一个java对象中的数据放入到redis缓存中. @SpringBootTest class SpringBoot06JdbcApplicationTests {@Autowiredprivate ...
- SpringBoot整合Redis储存对象
java对象以json的方式存储到redis中 通过set进redis中的数据,get不到 String cityKey ="city_"+id;ValueOperations&l ...
- springboot整合minio搭建对象储存及短链服务
搭建属于自己的对象储存服务及短链服务(Minio) 文档地址 minio官方文档: https://docs.min.io/?ref=ob minio 中文文档地址: http://docs.mini ...
- springboot整合腾讯云cos对象储存
一:腾讯云前期准备 直接在腾讯云中搜索"对象存储",立即使用 点击存储桶列表,创建存储桶 填写基本信息:所属地域,名称,访问权限(公有读写) 下一步,下一步,创建,存储桶创建成功 ...
- SpringBoot整合Mybatis超详细流程
SpringBoot整合Mybatis超详细流程 文章目录 SpringBoot整合Mybatis超详细流程 前言 详细流程 0.引入Mybatis 1.创建数据 2.创建程序目录 3.理解后台访问流 ...
- Springboot整合redis(lettuce)
springboot 整合redis(lettuce) 首先确保电脑上装了redis.最好能用redisDesktop查看一下数据情况 redis是一款非常流行的Nosql数据库.redis的功能非常 ...
- RabbitMQ,RabbitMQ 的工作模式,Spring 整合 RabbitMQ,Springboot 整合RabbitMQ
什么是RabbitMQ 1.1 MQ概述 MQ全称 Message Queue(消息队列),是在消息的传输过程中保存消息的容器.多用于分布式系统之间进行通信. ⚫ MQ,消息队列,存储消息的中间件 ⚫ ...
最新文章
- 从技术角度分析推荐系统案例
- 银行java多线程例子_Java 多线程 之 银行ATM实例
- 思科路由器动态NAT配置
- 根据当前日期算前一年、前一月、前一天(java基础)
- 吴恩达 ML作业提交:Grader sent no response
- 分布式集群环境下,如何实现session共享三(环境搭建)
- MySQL数据类型与操作
- match与index——vlookup的加强版
- Ubuntu+vscode打不开
- 观点 | 抛开炒作看知识图谱,为什么现在才爆发?
- 关于dubbo的几个问题
- 无基础学python能干什么-呼市学Python语言能干什么
- .Net报文请求转义
- 单片机之串行通信接口遇到的问题
- 谈谈超平面(hyperplane)
- 卷积神经网络之“浅层特征”与“深层特征”
- 7440 GT540
- 超级详细:Docker Commands —— Container Commands !(新手必看必会)
- 关于Fabric中shim包的问题
- Redis 部署方式(单点、master/slaver、sentinel、cluster) 概念与区别
热门文章
- C++中内存分配方式、空指针及野指针的区别
- file input 移动端选择文件夹_免费 |《MNN For Swift》移动端机器学习实战课程
- 起动缓慢_世界最大柴油机为何是压缩空气起动?那么它到底是如何起动的呢?...
- python selenium 小知识点整理笔记(更新中...)
- 存储过程返回结果集_PostgreSQL函数返回结果集
- cif t t操作流程图_Danish:STATA 操作正态检验、卡方检验和T检验
- 通过注册表修改打开方式
- 余承东宣布鸿蒙系统视频,余承东宣布鸿蒙系统开源:打造全球的操作系统
- web 导出文件时如何让用户选择路径_Visual Paradigm 教程[UML]:如何绘制动画UML活动图?...
- pla是什么计算机原理,计算机组成原理第05章 中央处理器(2硬布线控制器与PLA控制器).ppt...