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

  1. <properties>
  2. <jackson.version>2.8.3</jackson.version>
  3. <grpc.version>1.6.1</grpc.version>
  4. <os.plugin.version>1.5.0.Final</os.plugin.version>
  5. <protobuf.plugin.version>0.5.0</protobuf.plugin.version>
  6. <protoc.version>3.3.0</protoc.version>
  7. <grpc.netty.version>4.1.14.Final</grpc.netty.version>
  8. </properties>
  9. <dependencies>
  10. <dependency>
  11. <groupId>io.grpc</groupId>
  12. <artifactId>grpc-netty</artifactId>
  13. <version>${grpc.version}</version>
  14. </dependency>
  15. <dependency>
  16. <groupId>io.grpc</groupId>
  17. <artifactId>grpc-protobuf</artifactId>
  18. <version>${grpc.version}</version>
  19. </dependency>
  20. <dependency>
  21. <groupId>io.grpc</groupId>
  22. <artifactId>grpc-stub</artifactId>
  23. <version>${grpc.version}</version>
  24. </dependency>
  25. <dependency>
  26. <groupId>io.netty</groupId>
  27. <artifactId>netty-common</artifactId>
  28. <version>${grpc.netty.version}</version>
  29. </dependency>
  30. <dependency>
  31. <groupId>com.fasterxml.jackson.core</groupId>
  32. <artifactId>jackson-annotations</artifactId>
  33. <version>${jackson.version}</version>
  34. </dependency>
  35. <dependency>
  36. <groupId>com.fasterxml.jackson.core</groupId>
  37. <artifactId>jackson-core</artifactId>
  38. <version>${jackson.version}</version>
  39. </dependency>
  40. <dependency>
  41. <groupId>com.fasterxml.jackson.core</groupId>
  42. <artifactId>jackson-databind</artifactId>
  43. <version>${jackson.version}</version>
  44. </dependency>
  45. </dependencies>
  46. <build>
  47. <extensions>
  48. <extension>
  49. <groupId>kr.motd.maven</groupId>
  50. <artifactId>os-maven-plugin</artifactId>
  51. <version>${os.plugin.version}</version>
  52. </extension>
  53. </extensions>
  54. <plugins>
  55. <plugin>
  56. <groupId>org.xolstice.maven.plugins</groupId>
  57. <artifactId>protobuf-maven-plugin</artifactId>
  58. <version>${protobuf.plugin.version}</version>
  59. <configuration>
  60. <protocArtifact>com.google.protobuf:protoc:${protoc.version}:exe:${os.detected.classifier}</protocArtifact>
  61. <pluginId>grpc-java</pluginId>
  62. <pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact>
  63. </configuration>
  64. <executions>
  65. <execution>
  66. <goals>
  67. <goal>compile</goal>
  68. <goal>compile-custom</goal>
  69. </goals>
  70. </execution>
  71. </executions>
  72. </plugin>
  73. </plugins>
  74. </build>

注意版本号,如果包版本不一致可能会有classnotFound的error

b,编写proto3文件,

[java] view plain copy

  1. syntax = "proto3";
  2. option java_multiple_files = true;
  3. option java_package = "com.aiccms.device.grpc.lib";
  4. option java_outer_classname = "DeviceFixProto";
  5. option objc_class_prefix = "HLW";
  6. package device;
  7. // The device service definition.
  8. service DeviceFixService {
  9. // Sends a message
  10. rpc insertDeviceFix (deviceFix) returns (booleanReply){}
  11. rpc updateDeviceFix (deviceFix) returns (booleanReply){}
  12. rpc searchDeviceFix (conditionsRequest) returns (deviceFix){}
  13. rpc deleteDeviceFix (conditionsRequest) returns (booleanReply){}
  14. }
  15. // The request message .
  16. message conditionsRequest {
  17. string id = 1;
  18. }
  19. message deviceFix {
  20. string id=1;
  21. string serialNum=2;
  22. string userNum=3;
  23. int32  status=4;
  24. int32  type=5;
  25. string address=6;
  26. string createtime=7;
  27. string updatetime=8;
  28. }
  29. // The response message
  30. message booleanReply {
  31. bool reply = 1;
  32. }
  33. // The response message
  34. message objectReply {
  35. bool reply = 1;
  36. }

编写proto3文件,开头syntax中要指定为proto3版本。其他语法这里不做详细介绍。

c,使用mvn命令 protobuf:compile 和protobuf:compile-custom命令编译生成java文件

生成之后的文件在target目录中

注意:proto目录与java目录同级

d,以上这些都在一个公共的工程当中,因为这些类不管是客户端和服务端都要使用。

e,编写grpc服务端,首先添加maven依赖

[html] view plain copy

  1. <grpc.stater.version>1.3.0-RELEASE</grpc.stater.version>
  2. <dependency>
  3. <groupId>net.devh</groupId>
  4. <artifactId>grpc-server-spring-boot-starter</artifactId>
  5. <version>${grpc.stater.version}</version>
  6. </dependency>
f,服务端代码

[html] view plain copy

  1. /**
  2. * User: hmemb
  3. * Email: 949530857@qq.com
  4. * Date: 2018/1/9
  5. */
  6. @Slf4j
  7. @GrpcService(DeviceFixServiceGrpc.class)
  8. public class deviceGrpcService extends DeviceFixServiceGrpc.DeviceFixServiceImplBase{
  9. @Autowired
  10. private IDevicesFixService deviceService;
  11. @Override
  12. public void insertDeviceFix(deviceFix request, StreamObserver<booleanReply> responseObserver) {
  13. DevicesFix deviceFix = DevicesFix.builder().id(request.getId())
  14. .serialNum(request.getSerialNum())
  15. .address(request.getAddress())
  16. .createtime(DateUtil.toDate(request.getCreatetime(), DatePattern.TIMESTAMP))
  17. .updatetime(DateUtil.toDate(request.getUpdatetime(), DatePattern.TIMESTAMP))
  18. .userNum(request.getUserNum())
  19. .status(request.getStatus())
  20. .type(request.getType())
  21. .build();
  22. log.info(deviceFix.toString());
  23. boolean replyTag = deviceService.insert(deviceFix);
  24. booleanReply reply = booleanReply.newBuilder().setReply(replyTag).build();
  25. responseObserver.onNext(reply);
  26. responseObserver.onCompleted();
  27. }

g,在配置文件中添加配置信息

 

[html] view plain copy

  1. #grpc server config
  2. spring.application.name: device-grpc-server
  3. grpc.server.port:7052

h,编写客户端代码:引入maven依赖

[html] view plain copy

  1. <grpc.stater.version>1.3.0-RELEASE</grpc.stater.version
 

[html] view plain copy

  1. <dependency>
  2. <groupId>net.devh</groupId>
  3. <artifactId>grpc-client-spring-boot-starter</artifactId>
  4. <version>${grpc.stater.version}</version>
  5. </dependency>
i,编写gprc接口实现,注解@grpcClient 填写grpc接口名称
 

[java] view plain copy

  1. /**
  2. * User: hmemb
  3. * Email: 949530857@qq.com
  4. * Date: 2018/01/19
  5. */
  6. @Service
  7. @Slf4j
  8. public class DeviceGrpcService {
  9. @GrpcClient("device-grpc-server")
  10. private Channel serverChannel;
  11. public String insertDeviceFix( ){
  12. DeviceFixServiceGrpc.DeviceFixServiceBlockingStub stub = DeviceFixServiceGrpc.newBlockingStub(serverChannel);
  13. booleanReply response = stub.insertDeviceFix(
  14. deviceFix.newBuilder()
  15. .setId("UUID-O1")
  16. .setSerialNum("AUCCMA-01")
  17. .setAddress("SHENZHEN")
  18. .setCreatetime(DateUtil.toString(new Date(), DatePattern.TIMESTAMP))
  19. .setUpdatetime(DateUtil.toString(new Date(), DatePattern.TIMESTAMP))
  20. .setStatus(1)
  21. .setType(1)
  22. .build());
  23. log.info("grpc消费者收到:--》"+response.getReply());
  24. if(response.getReply()){
  25. return "success";
  26. }else{
  27. return "fail";
  28. }
  29. }
  30. }

j,配置文件中加入接口的服务端地址,grpc.client.[服务器规定的接口名称].post/host

 
 

[html] view plain copy

  1. grpc.client.device-grpc-server.host:127.0.0.1
  2. grpc.client.device-grpc-server.port:7052

k,封装成http rest接口测试

 

[java] view plain copy

  1. /**
  2. * @Author:Hmemb
  3. * @Description:
  4. * @Date:Created in 18:24 2018/1/18
  5. */
  6. @RestController
  7. @Api(value = "Testcontroller", description = "测试swagger")
  8. public class Testcontroller {
  9. @Autowired
  10. private DeviceGrpcService deviceGrpcService;
  11. @RequestMapping("/testInsertDeviceFix")
  12. @ApiOperation(value = "test", httpMethod = "GET", notes = "测试grpc插入")
  13. public String printMessage3(@RequestParam(defaultValue = "Hmemb") String name) {
  14. return deviceGrpcService.insertDeviceFix();
  15. }
  16. @RequestMapping("/TEST1")
  17. @ApiOperation(value = "test", httpMethod = "GET", notes = "测试1")
  18. public String printMessage(@RequestParam(defaultValue = "Michael") String name) {
  19. return name;
  20. }
  21. }

l,接口测试结果

 
我只实现了proto中的一个接口,其他接口同理。

转载于:https://my.oschina.net/xiaominmin/blog/1801385

springboot整合gprc 传输对象相关推荐

  1. SpringBoot整合——阿里云对象存储(OSS)

    SpringBoot整合--阿里云对象存储 1 OSS介绍 在开发应用的过程中,我们经常会有用户需要实名认证之后才能访问的需求. 用户认证需要上传证件图片.首页轮播也需要上传图片,因此我们要做文件服务 ...

  2. springboot整合阿里云对象存储oss

    知识梳理: 今天要学的知识很实用,一个合格的项目里面肯定会用到这个技术,那就是文件上传,文件上传可以帮我们上传头像.excel表格.等,用过文件上传的小伙伴都是文件上传到哪里去呢?本人第一次上传文件是 ...

  3. SpringBoot整合Redis存储对象数据是乱码数据解决方法

    将一个java对象中的数据放入到redis缓存中. @SpringBootTest class SpringBoot06JdbcApplicationTests {@Autowiredprivate ...

  4. SpringBoot整合Redis储存对象

    java对象以json的方式存储到redis中 通过set进redis中的数据,get不到 String cityKey ="city_"+id;ValueOperations&l ...

  5. springboot整合minio搭建对象储存及短链服务

    搭建属于自己的对象储存服务及短链服务(Minio) 文档地址 minio官方文档: https://docs.min.io/?ref=ob minio 中文文档地址: http://docs.mini ...

  6. springboot整合腾讯云cos对象储存

    一:腾讯云前期准备 直接在腾讯云中搜索"对象存储",立即使用 点击存储桶列表,创建存储桶 填写基本信息:所属地域,名称,访问权限(公有读写) 下一步,下一步,创建,存储桶创建成功 ...

  7. SpringBoot整合Mybatis超详细流程

    SpringBoot整合Mybatis超详细流程 文章目录 SpringBoot整合Mybatis超详细流程 前言 详细流程 0.引入Mybatis 1.创建数据 2.创建程序目录 3.理解后台访问流 ...

  8. Springboot整合redis(lettuce)

    springboot 整合redis(lettuce) 首先确保电脑上装了redis.最好能用redisDesktop查看一下数据情况 redis是一款非常流行的Nosql数据库.redis的功能非常 ...

  9. RabbitMQ,RabbitMQ 的工作模式,Spring 整合 RabbitMQ,Springboot 整合RabbitMQ

    什么是RabbitMQ 1.1 MQ概述 MQ全称 Message Queue(消息队列),是在消息的传输过程中保存消息的容器.多用于分布式系统之间进行通信. ⚫ MQ,消息队列,存储消息的中间件 ⚫ ...

最新文章

  1. 从技术角度分析推荐系统案例
  2. 银行java多线程例子_Java 多线程 之 银行ATM实例
  3. 思科路由器动态NAT配置
  4. 根据当前日期算前一年、前一月、前一天(java基础)
  5. 吴恩达 ML作业提交:Grader sent no response
  6. 分布式集群环境下,如何实现session共享三(环境搭建)
  7. MySQL数据类型与操作
  8. match与index——vlookup的加强版
  9. Ubuntu+vscode打不开
  10. 观点 | 抛开炒作看知识图谱,为什么现在才爆发?
  11. 关于dubbo的几个问题
  12. 无基础学python能干什么-呼市学Python语言能干什么
  13. .Net报文请求转义
  14. 单片机之串行通信接口遇到的问题
  15. 谈谈超平面(hyperplane)
  16. 卷积神经网络之“浅层特征”与“深层特征”
  17. 7440 GT540
  18. 超级详细:Docker Commands —— Container Commands !(新手必看必会)
  19. 关于Fabric中shim包的问题
  20. Redis 部署方式(单点、master/slaver、sentinel、cluster) 概念与区别

热门文章

  1. C++中内存分配方式、空指针及野指针的区别
  2. file input 移动端选择文件夹_免费 |《MNN For Swift》移动端机器学习实战课程
  3. 起动缓慢_世界最大柴油机为何是压缩空气起动?那么它到底是如何起动的呢?...
  4. python selenium 小知识点整理笔记(更新中...)
  5. 存储过程返回结果集_PostgreSQL函数返回结果集
  6. cif t t操作流程图_Danish:STATA 操作正态检验、卡方检验和T检验
  7. 通过注册表修改打开方式
  8. 余承东宣布鸿蒙系统视频,余承东宣布鸿蒙系统开源:打造全球的操作系统
  9. web 导出文件时如何让用户选择路径_Visual Paradigm 教程[UML]:如何绘制动画UML活动图?...
  10. pla是什么计算机原理,计算机组成原理第05章 中央处理器(2硬布线控制器与PLA控制器).ppt...