一,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中的一个接口,其他接口同理。
来源:oschina
链接:https://my.oschina.net/u/866802/blog/1801385