美文网首页
java实现gRpc服务端-客户端框架代码

java实现gRpc服务端-客户端框架代码

作者: xhh199090 | 来源:发表于2020-02-29 15:47 被阅读0次

参考官方github代码例子:https://github.com/grpc/grpc-java/tree/master/examples/src/main/java/io/grpc/examples/helloworld

一、idea安装protobuf插件

二、添加protobuf和grpc的pom依赖包和插件

依赖包

<properties>
    <protobuf.version>3.6.1</protobuf.version>
    <grpc.version>1.19.0</grpc.version>
</properties>

<dependencies>
    <dependency>
        <groupId>com.google.protobuf</groupId>
        <artifactId>protobuf-java</artifactId>
        <version>${protobuf.version}</version>
    </dependency>
    <dependency>
        <groupId>io.grpc</groupId>
        <artifactId>grpc-netty</artifactId>
        <version>${grpc.version}</version>
    </dependency>
    <dependency>
        <groupId>io.grpc</groupId>
        <artifactId>grpc-protobuf</artifactId>
        <version>${grpc.version}</version>
    </dependency>
    <dependency>
        <groupId>io.grpc</groupId>
        <artifactId>grpc-stub</artifactId>
        <version>${grpc.version}</version>
    </dependency>
</dependencies>

pom添加protobuf插件

<build>
    <extensions>
        <extension>
            <groupId>kr.motd.maven</groupId>
            <artifactId>os-maven-plugin</artifactId>
            <version>1.5.0.Final</version>
        </extension>
    </extensions>
    <plugins>
        <!--protobuf插件-->
        <plugin>
            <groupId>org.xolstice.maven.plugins</groupId>
            <artifactId>protobuf-maven-plugin</artifactId>
            <version>0.5.0</version>
            <configuration>
                <!--
                  The version of protoc must match protobuf-java. If you don't depend on
                  protobuf-java directly, you will be transitively depending on the
                  protobuf-java version that grpc depends on.
                -->
                <protocArtifact>
                    com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier}
                </protocArtifact>
                <pluginId>grpc-java</pluginId>
                <pluginArtifact>
                    io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}
                </pluginArtifact>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>compile</goal>
                        <goal>compile-custom</goal>
                        <goal>test-compile</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

三、编写Proto文件

注:编写proto文件,文件的格式可以参考Protobuf语言指南——.proto文件语法详解里面讲的很详细 https://blog.csdn.net/u014308482/article/details/52958148



.proto文件内容如下
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;
}

四、生成gRpc java代码

第一种方式:idea中执行如下

compile:用于生成protobuf类
compile-custom:生成rpc调用类,其中会用到compile过程中生成的protobuf类


第二种方式:

linux下执行命令:
mvn protobuf:compile
mvn protobuf:compile-custom //生成rpc调用类

在64位window环境下使用的命令:
mvn protobuf:compile -Dos.detected.name=windows -Dos.detected.arch=x86_64 -Dos.detected.classifier=windows-x86_64
mvn protobuf:compile-custom -Dos.detected.name=windows -Dos.detected.arch=x86_64 -Dos.detected.classifier=windows-x86_64
其中需要传入的三个参数:
os.detected.name
os.detected.arch
os.detected.classifier

最终生成如下文件,其中GreeterGrpc是一个很重要的类,直接关系到我们的服务,我们自己提供的服务需要继承它的一个内部类,在客户端中则是可以从中得到一个stub用于调用(例如:GreeterGrpc.GreeterBlockingStub)。


五、编写服务端-客户端代码

服务端代码主要两件事:
第一件,实现提供的业务服务,这是本职工作。
要实现提供的服务,只需要写一个类继承GreeterGrpc.GreeterImplBase这个类即可,然后因为我们定义的方法是SayHello,那么我们也实现这个方法,值得一提的是,需要注意一下这个方法的参数是固定的,不能随心所欲地写。

第二件,启动一个grpc服务器,用于接收客户端的请求。
其中主要是start方法用于启动服务器并接收客户端的请求。在server中添加名称解析服务服务实在构造方法中进行的。另外,blockUntilShutdown方法则会让server阻塞到程序退出为止。

代码如下:

private Server server;

private void start() throws IOException {
    /* The port on which the server should run */
    int port = 50051;
    server = ServerBuilder.forPort(port)
            .addService(new GreeterImpl())
            .build()
            .start();
    logger.info("Server started, listening on " + port);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            // Use stderr here since the logger may have been reset by its JVM shutdown hook.
            System.err.println("*** shutting down gRPC server since JVM is shutting down");
            try {
                HelloWorldServer.this.stop();
            } catch (InterruptedException e) {
                e.printStackTrace(System.err);
            }
            System.err.println("*** server shut down");
        }
    });
}

private void stop() throws InterruptedException {
    if (server != null) {
        server.shutdown().awaitTermination(30, TimeUnit.SECONDS);
    }
}

/**
 * Await termination on the main thread since the grpc library uses daemon threads.
 */
private void blockUntilShutdown() throws InterruptedException {
    if (server != null) {
        server.awaitTermination();
    }
}

/**
 * Main launches the server from the command line.
 */
public static void main(String[] args) throws IOException, InterruptedException {
    final HelloWorldServer server = new HelloWorldServer();
    server.start();
    server.blockUntilShutdown();
}

客户端代码参考样例。

相关文章

网友评论

      本文标题:java实现gRpc服务端-客户端框架代码

      本文链接:https://www.haomeiwen.com/subject/wagphhtx.html