springboot集成GRPC协议

开发人员联系方式:[email protected]
目的:springboot工程集成GRPC协议

一、添加maven依赖


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



   
        
            kr.motd.maven
            os-maven-plugin
            1.5.0.Final
        
    
    
        
            org.xolstice.maven.plugins
            protobuf-maven-plugin
            0.5.1
            
                com.google.protobuf:protoc:3.5.1-1:exe:${os.detected.classifier}
                grpc-java
                io.grpc:protoc-gen-grpc-java:1.17.1:exe:${os.detected.classifier}
            
            
                
                    
                        compile
                        compile-custom
                    
                
            
        
    

编写proto文件:HelloService.proto到main/proto目录

syntax = "proto3";
package grpc.api;
option java_package = "grpc.api";


message HelloRequest {
    string name = 1;
}

message HelloResponse {
    string name = 1;
    string status = 2;
}

// rpc 服务
service HelloService {
    rpc hello(HelloRequest) returns(HelloResponse) {}
}

运行maven package后会在classes里面生成相应的java客户端代码。

二、编写server服务提供端代码

@GrpcService
public class HelloServiceImpl extends HelloServiceGrpc.HelloServiceImplBase {

    @Override
    public void hello(HelloRequest request, StreamObserver responseObserver) {
        System.out.println("hello server");
        final HelloResponse.Builder replyBuilder = HelloResponse.newBuilder().setName("hello "+request.getName()).setStatus("success");
        responseObserver.onNext(replyBuilder.build());
        responseObserver.onCompleted();
    }
}

application.yml指定服务名及端口

grpc:
  server:
    port: 6000
spring:
  application:
    name: hello-grpc-server

三、编写client客户端调用代码

@Service
public class TestServiceImpl {
    @GrpcClient("hello-grpc-server") //指定服务名称
    private Channel serverChannel;
 
    public String hello(String name) {
        HelloServiceGrpc.HelloServiceBlockingStub stub = HelloServiceGrpc.newBlockingStub(serverChannel);
        HelloRequest.Builder builder= HelloRequest.newBuilder().setName(name);
        HelloResponse response = stub.hello(builder.build());
        return "{'responseStatus':'"+response.getStatus()+"','result':'"+response.getName()+"'}";
    }
}
@Controller
public class TestController {
    @Autowired
    private TestServiceImpl testService;

    @ResponseBody
    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public Object hello(@RequestParam String name) {
        String result = testService.hello(name);
        return result;
    }
}

application.yml配置

grpc:
  client:
    hello-grpc-server:
      address: static://localhost:6000   
      enableKeepAlive: true
      keepAliveWithoutCalls: true
      negotiationType: plaintext

注意:当服务端和客户端注册到同一个eureka时,可以不配置address,默认会在eureka里面找名为hello-grpc-server的服务,如果有多个服务还会默认使用负载均衡。当指定了address时,则该接口直接调用指定地址的服务。访问客户端 http://localhost:8080/hello?name=world 会调用服务端的hello方法。

你可能感兴趣的:(springboot集成GRPC协议)