springboot创建gRPC客户端


1. maven

   还没有springboot官方的gRPC客户端,使用的是net.devh



    net.devh
    grpc-client-spring-boot-starter
    2.13.1.RELEASE

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";
    }
    
}