创建一个基础的spring boot项目
导入第三方依赖1.8 1.6.1 0.6.1 2.4.0.RELEASE
更改bulidnet.devh grpc-client-spring-boot-starter ${grpc-client-spring-boot-starter} org.springframework.boot spring-boot-starter-web org.projectlombok lombok
修改配置文件kr.motd.maven os-maven-plugin ${os-maven-plugin.version} org.springframework.boot spring-boot-maven-plugin org.projectlombok lombok org.xolstice.maven.plugins protobuf-maven-plugin ${protobuf-maven-plugin.version} com.google.protobuf:protoc:3.5.1-1:exe:${os.detected.classifier} grpc-java io.grpc:protoc-gen-grpc-java:1.16.1:exe:${os.detected.classifier} compile compile-custom
grpc:
client:
GLOBAL:
negotiation-type: plaintext
# 修改客户端端默认入参最大大小,默认值为4M ,这里修改为20M 20*1024*1024
max-inbound-message-size: 20971520
# 客户端指定连接服务端地址
address: 'static://127.0.0.1:8989'
创建proto
创建proto文件夹
在main文件夹下创建proto文件。
创建.proto文件syntax = "proto3";
package com.example.grpc;
option java_multiple_files = true;
option java_package = "com.example.grpc.lib";
option java_outer_classname = "HelloWorldProto";
// The greeting service definition.
service MyService {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {
}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}
编译
如果出现编译异常问题。有可能是yaml文件编码问题,更改成utf-8编码就可以了。
@GrpcClient(value = “test-client”)
private MyServiceGrpc.MyServiceBlockingStub simpleStub;
其中Mysercie是你.proto中的service 。
@Service
public class MyGrpcClientService {
@GrpcClient(value = "test-client")
private MyServiceGrpc.MyServiceBlockingStub simpleStub;
public String sendMessage(final String name) {
try {
final HelloReply response = simpleStub.sayHello(HelloRequest.newBuilder().setName(name).build());
return response.getMessage();
} catch (final StatusRuntimeException e) {
return "FAILED with " + e.getStatus().getCode().name();
}
}
}
验证
编写测试接口
在grpc-client中编写一个简单接口。
创建一个controller文件夹,编写一个TestController.java
@RestController
public class TestController {
@Resource
private MyGrpcClientService testService;
@GetMapping("/test")
public Object test(String name){
return testService.sendMessage(name);
}
}
分别启动server端和client端,在使用postman进行调用测试。
调用 成功
到了这一步,grpc简单使用已经完成。最后我们只需要让甲方提供给 我们proto文件夹 进行编译下, 然后编写我们的业务代码就可以了。
交流群java交流群: 868794080
参考资料grpc框架参考资料



