Springboot之接入gRPC

1、maven依赖


    
    3.5.1
    0.6.1
    1.42.1
    1.6.0




    io.grpc
    grpc-stub
    ${grpc.version}


    io.grpc
    grpc-protobuf
    ${grpc.version}


    io.grpc
    grpc-netty
    ${grpc.version}

2、编译环境构建


    
        
        
            kr.motd.maven
            os-maven-plugin
            ${os-maven-plugin.version}
        
    
    
        
        
            org.xolstice.maven.plugins
            protobuf-maven-plugin
            ${protobuf-plugin.version}
            
                com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier}
                grpc-java
                io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}
                
                ${project.basedir}/src/main/proto
                ${project.basedir}/src/main/java
                
                false
            
            
                
                    
                        compile
                        compile-custom
                    
                
            
        

    
        

3、添加proto文件

在src/java同级添加proto文件夹,内部添加proto文件

Springboot之接入gRPC_第1张图片

修改java_package,生成包路径

syntax = "proto3";

option java_multiple_files = true;
option java_package = "com.bhl.biz.grpc";

package media_broker;

// The service definition.
service MediaBroker {
  rpc open(MediaObject) returns (MediaStatus) {};

  rpc fetchFrame(MediaObject) returns (FrameObject) {};
  rpc fetchImage(MediaObject) returns (ImageObject) {};

  rpc close(MediaObject) returns (MediaStatus) {};
}

message MediaObject {
  string address = 1;
}

message MediaStatus {
  bool status = 1;
  string message = 2;
}

4、生成代码

依次执行protobuf:compile、compile-custom

Springboot之接入gRPC_第2张图片

随后生成对应代码文件

Springboot之接入gRPC_第3张图片

5、注册grpc

官方参考demo

https://github.com/grpc/grpc-java/blob/master/examples/src/main/java/io/grpc/examples/helloworld/HelloWorldClient.java

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

private ManagedChannel channel;
private MediaBrokerGrpc.MediaBrokerBlockingStub blockingStub;

void init(){
    // 127.0.0.1 50051
    channel = ManagedChannelBuilder.forAddress(grpcConfig.getHost(), grpcConfig.getPort()).usePlaintext().build();
    blockingStub = MediaBrokerGrpc.newBlockingStub(channel);
}

核心文件 MediaBrokerGrpc

三种通信方式

Springboot之接入gRPC_第4张图片

6、发送请求

请求为已注册的服务

Springboot之接入gRPC_第5张图片

// 请求对象
MediaObject object = MediaObject.newBuilder().setAddress(address).build();
// 发送请求
MediaStatus status = blockingStub.open(object);
log.info(status.toString());
boolean result = status.getStatus();

你可能感兴趣的:(Spring,Boot场景案例,spring,boot,java,rpc)