轉自:http://www.saily.top/2017/07/23/netty5/
gRPC
Define your service using Protocol Buffers, a powerful binary serialization toolset and language
gRPC是基於Protobuf開發的RPC框架,簡化了protobuf的開發,提供了服務端和客戶端網絡交互這一塊的代碼。
Demo
照着https://grpc.io/docs/quickstart/java.html測試一下官方的Demo。
記得要把Update a gRPC service
部分做了。
gRPC整合Gradle與代碼生成
https://github.com/grpc/grpc-java
這個是gRPC-java項目,先引入gRPC的依賴。
1 |
compile 'io.grpc:grpc-netty:1.4.0' |
然后配置gradle的grpc插件
1 |
apply plugin: 'java' |
后面直接用gradle的任務就可以生成代碼了。
gRPC提供了3種傳輸層的實現
-
gRPC comes with three Transport implementations:
- The Netty-based transport is the main transport implementation based on Netty. It is for both the client and the server.
- The OkHttp-based transport is a lightweight transport based on OkHttp. It is mainly for use on Android and is for client only.
- The inProcess transport is for when a server is in the same process as the client. It is useful for testing.
https://github.com/google/protobuf-gradle-plugin
The Gradle plugin that compiles Protocol Buffer (aka. Protobuf) definition files (*.proto) in your project. There are two pieces of its job:
- It assembles the Protobuf Compiler (protoc) command line and use it to generate Java source files out of your proto files.
- It adds the generated Java source files to the input of the corresponding Java compilation unit (sourceSet in a Java project; variant in an Android project), so that they can be compiled along with your Java sources.
實戰
配置好后,進行一個演示
在src/main/proto
新建一個文件Student.proto
gradle插件默認從src/main/proto
找proto源文件進行代碼生成,這里有提到,而且這個路徑的配置是可以修改的。
1 |
syntax = "proto3"; |
然后執行gradle generateProto
,生成的代碼默認是放在/build
目錄下,我們手動拷貝到src/main/java
。
實現代碼
1 |
package com.sail.grpc; |
服務器端
1 |
package com.sail.grpc; |
客戶端
1 |
package com.sail.grpc; |