定义服务接口
syntax = "proto3";
option java_multiple_files = true;
option java_package = "com.github.xjs.grpcapi";
option java_outer_classname = "ProductProto";
package product;
service ProductInfo {
rpc getProduct(ProductId) returns(Product);
}
message Product {
string id = 1;
string name=2;
string description=3;
float price=4;
}
message ProductId {
string value = 1;
}
服务端
首先添加相关依赖:
xml
<dependency>
<groupId>net.devh</groupId>
<artifactId>grpc-server-spring-boot-starter</artifactId>
<version>2.15.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
添加相关的配置
yml
server:
port: 8080
spring:
application:
# 这个名字很重要,客户端调用的时候需要指定这个名字
name: product-service
grpc:
server:
port: 9090
服务端service代码:
java
@GrpcService
public class ProductInfoImpl extends ProductInfoGrpc.ProductInfoImplBase {
@Override
public void getProduct(ProductId request, StreamObserver<Product> responseObserver) {
System.out.println(TextFormat.printer().escapingNonAscii(false).printToString(request));
Product product = Product.newBuilder().setId(request.getValue()).setName("三国演义").build();
responseObserver.onNext(product);
responseObserver.onCompleted();
}
}
客户端
添加依赖
xml
<dependency>
<groupId>net.devh</groupId>
<artifactId>grpc-client-spring-boot-starter</artifactId>
<version>2.15.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
添加配置
yml
server:
port: 8081
spring:
application:
name: product-client-service
grpc:
client:
# #服务名称不能写错,这个需要和server端spring.application.name的定义的名称一致
product-service:
address: "static://localhost:9090"
# 是否开启保持连接(长连接)
enableKeepAlive: true
# 保持连接时长(默认20s)
keepAliveTimeout: 20s
# 没有RPC调用时是否保持连接(默认false,可禁用避免额外消耗CPU)
keepAliveWithoutCalls: false
# 客户端负载均衡策略(round_robin(默认), pick_first)
defaultLoadBalancingPolicy: round_robin
# 通信类型
# plaintext | plaintext_upgrade | tls
# 明文通信且http/2 | 明文通信且升级http/1.1为http/2 | 使用TLS(ALPN/NPN)通信
negotiationType: plaintext
客户端调用:
java
@RestController
public class ProductController {
// 这个名字是远程要调用的服务的名字,跟配置文件要对应起来
@GrpcClient("product-service")
private ProductInfoGrpc.ProductInfoBlockingStub stub;
@GetMapping("/getProductById")
public ProductDTO getProductById(Long id){
ProductId productId = ProductId.newBuilder().setValue(""+id).build();
Product product = stub.getProduct(productId);
return ProductDTO.of(product);
}
}
完整的源码下载:https://github.com/xjs1919/learning-demo/tree/master/grpc-demo