maven集成Protobuff并创建GRpc示例

1. 创建protobuff文件:

syntax = "proto3";

option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";

package helloworld;

// The greeting service definition.
service Greeter {
  // 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;
}

具体写法可以搜索:protobuff


2.  添加gRPC-java的依赖:


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

我的grpc-version为1.8.0

可以在maven查看grpc-all的各个版本,每个版本对应的protobuff-java版本不一样,1.8.0对应的是3.4.0,但我后面的插件对应的版本是3.3.1,所以会下两个版本。看其他帖子说必须得保证两个版本一致,但我的不一致也可以。

3. 添加protocol buffers编译插件:

可以搜maven protoc查看相关资料

  • 
        
            
                kr.motd.maven
                os-maven-plugin
                1.4.1.Final
            
        
        
            
                org.xolstice.maven.plugins
                protobuf-maven-plugin
                0.5.0
                
                    
                    com.google.protobuf:protoc:3.5.0:exe:${os.detected.classifier}
                    grpc-java
                    io.grpc:protoc-gen-grpc-java:${grpc-version}:exe:${os.detected.classifier}
                
                
                    
                        
                            compile
                            compile-custom
                        
                    
                
            
        
    
  • 其中os-maven-plugin用于识别你的操作系统的版本,提供${os.detected.classifier}参数供后面使用,没有其他的作用。我使用了1.5.0-Final,结果得不到${os.detected.classifier}属性,所以换了低版本的1.4.1.Final
  • grpc-version和你grpc-all依赖的版本一致,我的是1.8.0

  • 该插件用于配置protoc,会生成相应的插件:
  • maven集成Protobuff并创建GRpc示例_第1张图片

  • 4. 运行第一个插件(compile):
  • maven集成Protobuff并创建GRpc示例_第2张图片
  • 生成一堆java文件和一个.exe文件,可以看到生成的protoc后面有一串3.5.0,这个是在写protobuf-maven-plugin插件的时候在中配置的。后缀windows-x86_64的系统版本标识,是由os-maven-plugin插件获得的。
  • 5. 运行第二个插件(compile-custom):
  • maven集成Protobuff并创建GRpc示例_第3张图片
  • 他会生成一个exe文件和一个java文件
  • 6. 编写服务端代码:
  • package com.zj.layoutserver.server;
    import io.grpc.Server;
    import io.grpc.ServerBuilder;
    import io.grpc.examples.helloworld.GreeterGrpc;
    import io.grpc.examples.helloworld.HelloReply;
    import io.grpc.examples.helloworld.HelloRequest;
    import io.grpc.stub.StreamObserver;
    
    import java.io.IOException;
    
    public class HelloWorldServer {
    
    
        private int port = 50051;
        private Server server;
    
        private void start() throws IOException {
            server = ServerBuilder.forPort(port)
                    .addService(new GreeterImpl())
                    .build()
                    .start();
    
            System.out.println("service start...");
    
            Runtime.getRuntime().addShutdownHook(new Thread() {
    
                @Override
                public void run() {
    
                    System.err.println("*** shutting down gRPC server since JVM is shutting down");
                    HelloWorldServer.this.stop();
                    System.err.println("*** server shut down");
                }
            });
        }
    
        private void stop() {
            if (server != null) {
                server.shutdown();
            }
        }
    
        // block 一直到退出程序
        private void blockUntilShutdown() throws InterruptedException {
            if (server != null) {
                server.awaitTermination();
            }
        }
    
    
        public static void main(String[] args) throws IOException, InterruptedException {
    
            final HelloWorldServer server = new HelloWorldServer();
            server.start();
            server.blockUntilShutdown();
        }
    
    
        // 实现 定义一个实现服务接口的类
        private class GreeterImpl extends GreeterGrpc.GreeterImplBase {
    
    
            public void sayHello(HelloRequest req, StreamObserver responseObserver) {
                System.out.println("service:"+req.getName());
                HelloReply reply = HelloReply.newBuilder().setMessage(("Hello: " + req.getName())).build();
                responseObserver.onNext(reply);
                responseObserver.onCompleted();
            }
        }
    }
    7. 编写客户端代码:
  • package com.zj.layoutserver.client;
    
    import io.grpc.ManagedChannel;
    import io.grpc.ManagedChannelBuilder;
    import io.grpc.examples.helloworld.GreeterGrpc;
    import io.grpc.examples.helloworld.HelloReply;
    import io.grpc.examples.helloworld.HelloRequest;
    
    import java.util.concurrent.TimeUnit;
    
    public class HelloWorldClient {
    
        private final ManagedChannel channel;
        private final GreeterGrpc.GreeterBlockingStub blockingStub;
    
    
        public HelloWorldClient(String host,int port){
            channel = ManagedChannelBuilder.forAddress(host,port)
                    .usePlaintext(true)
                    .build();
    
            blockingStub = GreeterGrpc.newBlockingStub(channel);
        }
    
    
        public void shutdown() throws InterruptedException {
            channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
        }
    
        public  void greet(String name){
            HelloRequest request = HelloRequest.newBuilder().setName(name).build();
            HelloReply response = blockingStub.sayHello(request);
            System.out.println(response.getMessage());
    
        }
    
        public static void main(String[] args) throws InterruptedException {
            HelloWorldClient client = new HelloWorldClient("127.0.0.1",50051);
            for(int i=0;i<5;i++){
                client.greet("world:"+i);
            }
    
        }
    }
    然后依次运行服务端和客户端就可以了。
  • 有很多原理可以参考网上的其他教程

你可能感兴趣的:(研发管理)