千家信息网

使用Grpc+maven定义接口、发布服务、调用服务

发表于:2024-10-20 作者:千家信息网编辑
千家信息网最后更新 2024年10月20日,项目使用maven构建,执行mvn compile 命令后,proto文件自动生成java文件,这个功能需要依赖相关编译插件。一、pom.xml配置 4.0.0 com.test.grpcTest
千家信息网最后更新 2024年10月20日使用Grpc+maven定义接口、发布服务、调用服务

项目使用maven构建,执行mvn compile 命令后,proto文件自动生成java文件,这个功能需要依赖相关编译插件。
一、pom.xml配置

  4.0.0  com.test.grpcTest  grpc-api  0.0.1-SNAPSHOT  jar``  grpc-api      UTF-8                          io.grpc            grpc-netty            1.0.0                            io.grpc            grpc-protobuf            1.0.0                            io.grpc            grpc-stub            1.0.0                                        io.grpc                        grpc-all                        0.13.2                                                           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.0.0:exe:${os.detected.classifier}                    grpc-java                    io.grpc:protoc-gen-grpc-java:1.0.0:exe:${os.detected.classifier}                                                                                                        compile                            compile-custom                                                                                    

二、proto文档(IDL文档)编辑和编译成java文件

//指定proto3格式syntax = "proto3";//一些生成代码的设置option java_multiple_files = false;//以非外部类模式生成option java_package = "com.test.grpcTest.grpc_api";//所在包名option java_outer_classname = "Grpc";//最外层类名称message UnaryRequest{    string serviceName = 1;    string methodName = 2;    bytes data = 3;    string request_id = 4;//参数默认都为可选,如果没有赋值,那么接口中不会出现该参数,不会默认为null之类的}message UnaryResponse{    string serviceName = 1;    string methodName = 2;    bytes data = 3;    string request_id = 4;}service GrpcService{    // 一对一服务请求    rpc SendUnaryRequest(UnaryRequest) returns(UnaryResponse);}
proto文件编辑好后,在项目根目录下执行 **mvn compile** 进行编译 。如果使用maven编译proto文件,那么需要默认将proto文件放在 /src/main/proto/  路径下。编译后生成的java文件在 target/generated-sources/  路径下。将 java 文件拷贝到  /src/main/java/ 路径下。项目文件结构如下:

三、服务端代码
在 /src/main/java/ 路径下新建目录 /server,存放服务端代码。

package com.test.grpcTest.grpc_api.server;import com.test.grpcTest.grpc_api.GrpcServiceGrpc;import com.test.grpcTest.grpc_api.UnaryRequest;import com.test.grpcTest.grpc_api.UnaryResponse;import com.google.protobuf.ByteString;import io.grpc.Server;import io.grpc.ServerBuilder;import io.grpc.stub.StreamObserver;import java.io.IOException;//Grpc服务器对象public class GrpcServer {    private int port = 50051;//grpc服务端口    private Server server;//grpc server    public static void main(String[] args) throws IOException,InterruptedException {        final GrpcServer server = new GrpcServer();        server.start();        server.blockUntilShutdown();    }    private void start() throws IOException {        //指定grpc服务器端口、接口服务对象,启动grpc服务器        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");                GrpcServer.this.stop();                System.err.println("*** server shut down");            }        });    }    private void blockUntilShutdown() throws InterruptedException {        if (server != null) {            server.awaitTermination();        }    }    private void stop() {        if (server != null) {            server.shutdown();        }    }//内部类,继承抽象类 GrpcServiceGrpc.GrpcServiceImplBase,//并重写服务方法 sendUnaryRequest    private class GreeterImpl extends GrpcServiceGrpc.GrpcServiceImplBase {//UnaryRequest 客户端请求参数,//StreamObserver 返回给客户端的封装参数        public void sendUnaryRequest(UnaryRequest request,StreamObserver responseObserver) {            ByteString message = request.getData();            System.out.println("server, serviceName:" + request.getServiceName()                + "; methodName:" + request.getMethodName()+"; datas:"+new String(message.toByteArray()));            UnaryResponse.Builder builder = UnaryResponse.newBuilder();            builder.setServiceName("GrpcServiceResponse").setMethodName("sendUnaryResponse");            responseObserver.onNext(builder.build());            responseObserver.onCompleted();        }    }}

服务端输出日志:

四、客户端代码

package com.test.grpcTest.grpc_api.client;import java.util.concurrent.TimeUnit;import com.test.grpcTest.grpc_api.GrpcServiceGrpc;import com.test.grpcTest.grpc_api.UnaryRequest;import com.test.grpcTest.grpc_api.UnaryResponse;import com.google.protobuf.ByteString;import io.grpc.ManagedChannel;import io.grpc.ManagedChannelBuilder;//grpc客户端类public class GrpcClient {    private final ManagedChannel channel;//客户端与服务器的通信channel    private final GrpcServiceGrpc.GrpcServiceBlockingStub blockStub;//阻塞式客户端存根节点    public GrpcClient(String host, int port) {        channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext(true).build();//指定grpc服务器地址和端口初始化通信channel        blockStub = GrpcServiceGrpc.newBlockingStub(channel);//根据通信channel初始化客户端存根节点    }    public void shutdown() throws InterruptedException{        channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);    }    //客户端方法    public void sayHello(String str){        //封装请求参数        UnaryRequest request = UnaryRequest.newBuilder()            .setServiceName("GrpcServiceRequest").setMethodName("sendUnaryRequest").setData(ByteString.copyFrom(str.getBytes()))            .build();        //客户端存根节点调用grpc服务接口,传递请求参数        UnaryResponse response = blockStub.sendUnaryRequest(request);        System.out.println("client, serviceName:"+response.getServiceName()+"; methodName:"+response.getMethodName());    }    public static void main(String[] args) throws InterruptedException{        //初始化grpc客户端对象        GrpcClient client = new GrpcClient("127.0.0.1",50051);        for(int i=0; i<5; i++){            client.sayHello("client word:"+ i);            Thread.sleep(3000);        }    }}

客户端输出日志:

服务 客户 客户端 文件 参数 服务器 编译 代码 路径 接口 存根 对象 端口 节点 项目 生成 通信 文档 方法 日志 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 网络安全保障网络数据的什么能力 中国社科院数据库的技术支持 硬件开发和软件开发哪个难 5线的服务器风扇怎么接线 arm系统下软件开发 深海搁浅哪个服务器好一些 开创网络技术工作室 一梦江湖选择哪个服务器 数据库中的salt是什么 数据库建模面试题 北京智能软件开发在线咨询 拼多多平台服务器是干嘛的 数据库集群软件解压 软件开发的六个文档 什么叫数据库的管理系统 管理十个门店的服务器什么价 TD数据库中表重复创建 药物警戒安全数据库 复制数据库 表 ai智能语音视频服务器 卫生健康领域行业网络安全监督 数据库导入的文件可以查看出来吗 公安部网络安全保卫局李菁菁 第一届赣网杯网络安全大赛 通信网络安全展会 蓝盾股份网络安全产品 微信二维码服务器不显示 迅雷网数据库叫什么意思 网络安全工程师 数据库与应用实践技术
0