GRPC入门及Server Client示范

GRPC

GRPC是谷歌google出的一款RPC框架,RPC是远程过程调用remote procedure call,就是像调用本地方法一样调用远程机器上的方法

提供被调用的方法写在xxx.proto文件中,然后我们利用maven的compile编译生成代码,然后将定义的那些方法实现即可。绑定端口启动服务器即可提供这些方法被需要的人调用。

调用者使用stub来调用这些方法,返回结果。

  • demo项目结构

在这里插入图片描述

  • Test.proto文件

    syntax = "proto3";
    
    option java_multiple_files = true;
    option java_package = "com.example.grpc_java_demo";
    option java_outer_classname = "Test";
    option objc_class_prefix = "xlf";
    
    package test;
    
    //定义服务
    service TestService {
        //注意:这里是returns 不是return
        rpc SayHello(Request) returns (Response){
    
        }
    }
    //定义参数类型
    message Request {
        string message=1;
    }
    message Response {
        string message=1;
    }
    
    
    
  • 服务提供端类

    package com.example.grpc_java_demo.server;
    
    
    import com.example.grpc_java_demo.*;
    import com.google.protobuf.Descriptors;
    import io.grpc.Server;
    import io.grpc.ServerBuilder;
    import io.grpc.stub.StreamObserver;
    
    import java.io.IOException;
    import java.util.Map;
    
    /**
     * 服务端
     */
    public class TestServer {
        //定义端口
        private final int port = 50051;
        //服务
        private Server server;
    
        //启动服务,并且接受请求
        private void start() throws IOException {
            server = ServerBuilder.forPort(port).addService(new TestImpl()).build().start();
            System.out.println("服务开始启动-------");
            Runtime.getRuntime().addShutdownHook(new Thread() {
                @Override
                public void run() {
                    System.err.println("------shutting down gRPC server since JVM is shutting down-------");
                    System.err.println("调用者断开连接");
                    TestServer.this.stop();
                    System.err.println("------server shut down------");
                }
            });
        }
    
        //stop服务
        private void stop() {
            if (server != null) {
                server.shutdown();
            }
        }
        //server阻塞到程序退出
        private void  blockUntilShutdown() throws InterruptedException {
            if (server!=null){
                server.awaitTermination();
            }
        }
    
        //实现服务接口的类
        private class TestImpl extends TestServiceGrpc.TestServiceImplBase {
            @Override
            public void sayHello(Request request, StreamObserver<Response> responseObserver) {
                String msg=request.getMessage()+"我是服务器";
                System.err.println("收到请求:"+request.getMessage()+" 回复:"+msg);
                Response build = Response.newBuilder().setMessage(msg).build();
                //onNext()方法向客户端返回结果
                responseObserver.onNext(build);
                //告诉客户端这次调用已经完成
                responseObserver.onCompleted();
            }
        }
        public static void main(String[] args) throws IOException, InterruptedException {
            final  TestServer server=new TestServer();
            server.start();
            server.blockUntilShutdown();
        }
    }
    
    
    
  • 调用端client

    构建所需参数,调用stub里的方法即可完成。

    package com.example.grpc_java_demo.client;
    
    import com.example.grpc_java_demo.*;
    import io.grpc.ManagedChannel;
    import io.grpc.ManagedChannelBuilder;
    
    import java.util.concurrent.TimeUnit;
    /**
     * 客户端
     */
    public class TestClient {
        private final ManagedChannel channel;
        private final TestServiceGrpc.TestServiceBlockingStub blockingStub;
        private static final String host="127.0.0.1";
        private static final int ip=50051;
        public TestClient(String host,int port){
            //usePlaintext表示明文传输,否则需要配置ssl
            //channel  表示通信通道
            channel= ManagedChannelBuilder.forAddress(host, port).usePlaintext(true).build();
            //存根
            blockingStub=TestServiceGrpc.newBlockingStub(channel);
        }
        public void shutdown() throws InterruptedException {
            channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
        }
        public void  sayHello(){
            String msg="你好";
            System.err.println("发送:"+msg);
            Request request=Request.newBuilder().setMessage(msg).build();
            Response response=blockingStub.sayHello(request);
            System.err.println("收到回复:"+response.getMessage());
        }
        public static void main(String[] args) throws InterruptedException {
            TestClient client=new TestClient(host,ip);
            client.sayHello();
            client.shutdown();
        }
    }
    
    

    服务器收到的请求参数:

    调用者收到的回复

在这里插入图片描述

posted @ 2020-12-10 13:51  HumorChen99  阅读(0)  评论(0编辑  收藏  举报  来源