springboot整合gprc 傳輸物件
一,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檔案:
<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檔案,
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依賴
<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,服務端程式碼 /** * User: hmemb * Email: [email protected] * 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,在配置檔案中新增配置資訊 #grpc server config spring.application.name: device-grpc-server grpc.server.port:7052
h,編寫客戶端程式碼:引入maven依賴
<grpc.stater.version>1.3.0-RELEASE</grpc.stater.version <dependency> <groupId>net.devh</groupId> <artifactId>grpc-client-spring-boot-starter</artifactId> <version>${grpc.stater.version}</version> </dependency> i,編寫gprc介面實現,註解@grpcClient 填寫grpc介面名稱 /** * User: hmemb * Email: [email protected] * 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 grpc.client.device-grpc-server.host:127.0.0.1 grpc.client.device-grpc-server.port:7052
k,封裝成http rest介面測試 /** * @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中的一個介面,其他介面同理。 --------------------- 作者:Carlos_v 來源:CSDN 原文:https://blog.csdn.net/qq_28423433/article/details/79108976?utm_source=copy 版權宣告:本文為博主原創文章,轉載請附上博文連結!