一,grpc簡介:html
GRPC是google開源的一個高性能、跨語言的RPC框架,基於HTTP2協議,基於protobuf 3.x,基於Netty 4.x +。GRPC與thrift、avro-rpc等其實在整體原理上並無太大的區別,簡而言之GRPC並無太多突破性的創新。java
對於開發者而言:python
1)須要使用protobuf定義接口,即.proto文件android
2)而後使用compile工具生成特定語言的執行代碼,好比JAVA、C/C++、Python等。相似於thrift,爲了解決跨語言問題。git
3)啓動一個Server端,server端經過偵聽指定的port,來等待Client連接請求,一般使用Netty來構建,GRPC內置了Netty的支持。github
4)啓動一個或者多個Client端,Client也是基於Netty,Client經過與Server創建TCP常連接,併發送請求;Request與Response均被封裝成HTTP2的stream Frame,經過Netty Channel進行交互。spring
二,proto3:json
Protocol Buffers是一個跨語言、跨平臺的具備可擴展機制的序列化數據工具。也就是說,我在ubuntu下用python語言序列化一個對象,並使用http協議傳輸到使用java語言的android客戶端,java使用對用的代碼工具進行反序列化,也能夠獲得對應的對象。聽起來好像跟json沒有多大區別。。。其實區別挺多的。ubuntu
Google說protobuf是smaller,faster,simpler,咱們使用google規定的proto協議定義語言,以後使用proto的工具對代碼進行「編譯」,生成對應的各個平臺的源代碼,咱們可使用這些源代碼進行工做。springboot
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中的一個接口,其餘接口同理。