ransport
The Transport layer does the heavy lifting of putting and taking bytes off the wire. The interfaces to it are abstract just enough to allow plugging in of different implementations. Note the transport layer API is considered internal to gRPC and has weaker API guarantees than the core API under package io.grpc.
gRPC comes with multiple Transport implementations:
- The Netty-based HTTP/2 transport is the main transport implementation based on Netty. It is not officially supported on Android.
- The OkHttp-based HTTP/2 transport is a lightweight transport based on Okio and forked low-level parts of OkHttp. It is mainly for use on Android.
- The in-process transport is for when a server is in the same process as the client. It is used frequently for testing, while also being safe for production use.
- The Binder transport is for Android cross-process communication on a single device.
四种通信模式
-
简单rpc - 一个请求一个响应
rpc getRealNameByUsername (StudentRequest) returns (StudentResponse) {}
-
服务端流式rpc - 服务端流式响应
rpc getRealNameByUsernameLike (StudentUsernameRequest) returns (stream StudentResponse) {}
-
客户端流式rpc - 客户端流式请求
rpc getRealNameByUsernames (stream StudentUsernameRequest) returns (StudentResponseList) {}
-
双向流rpc
rpc getRealNamesByUsernames (stream StudentUsernameRequest) returns (stream StudentResponse) {}
高级应用
- 拦截器
- Stream Tracer - 流拦截器
- Retry Policy - 客户端重试
- NameResolver - 服务发现
- 负载均衡
- grpc与微服务:与dubbo、gateway、jwt、nacos2.x、openfeign
基础示例
本小节将使用简单的示例说明grpc-java的使用方法。
.proto文件
.proto文件需要放在src/main/proto目录下面:
syntax = "proto3";
package org.net5ijy.grpc.auto;
option java_package = "org.net5ijy.grpc.auto";
option java_outer_classname = "StudentRpc";
option java_multiple_files = true;
service StudentService {
rpc getRealNameByUsername (StudentUsernameRequest) returns (StudentResponse) {}
rpc getRealNameByUsernameLike (StudentUsernameRequest) returns (stream StudentResponse) {}
rpc getRealNameByUsernames (stream StudentUsernameRequest) returns (StudentResponseList) {}
rpc getRealNamesByUsernames (stream StudentUsernameRequest) returns (stream StudentResponse) {}
}
message StudentUsernameRequest {
string username = 1;
}
message StudentResponse {
string realName = 1;
}
message StudentResponseList {
repeated StudentResponse studentResponse = 1;
}
pom依赖
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty-shaded</artifactId>
<version>1.56.0</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>1.56.0</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>1.56.0</version>
</dependency>
pom插件
<build>
<finalName>${project.artifactId}</finalName>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.7.1</version>
</extension>
</extensions>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</a