springboot创建gRPC客户端
1. maven
还没有springboot官方的gRPC客户端,使用的是net.devh
<!-- gRPC --> <dependency> <groupId>net.devh</groupId> <artifactId>grpc-client-spring-boot-starter</artifactId> <version>2.13.1.RELEASE</version> </dependency>
2. application.properties
dl-server自命名,在后面使用
######################gRPC################## grpc.client.dl-server.address=static://127.0.0.1:9999 grpc.client.dl-server.enable-keep-alive=true grpc.client.dl-server.keep-alive-without-calls=true grpc.client.dl-server.negotiation-type=plaintext
3. 将proto文件生成的类放到一个包里
4. 创建一个服务类
@Service public class GrpcClientService { @GrpcClient("dl-server") private PlatformGrpc.PlatformBlockingStub pbStub; public String send(final String name, String id) { try { DlRequest req = DlRequest.newBuilder().setName(name).setId(id).build(); DlReply rep = pbStub.getDl(req); System.out.println(rep.getRes()); }catch(StatusRuntimeException sre) { System.out.println("src-1:"+sre.getMessage()); System.out.println("src-2:"+sre.getStatus().getCode().name()); return "error-src"; //no server:UNAVAILABLE }catch(Exception e) { System.out.println("e---"); return "error-e"; } return "ok"; } }
5. gRPC的代码化配置
@Configuration public class GrpcClientConfig { /** * 配置方式一:在application.properties配置 * 配置方式二,通过init() */ @PostConstruct private void init() { ManagedChannel mc = ManagedChannelBuilder.forAddress("127.0.0.1", 999).usePlaintext().build(); pbInitStub = PlatformGrpc.newBlockingStub(mc); } }