参考:

  1. java下使用gRPC的helloworld的demo实现javascript:void(0)
  2. grpc官方文档中文版 javascript:void(0)
  3. 示例:https://github.com/grpc/grpc-java/tree/master/examples/src/main/java/io/grpc/examples

具体实施步骤:

1、新建一个普通的Maven项目:

java下使用gRPC的helloworld的demo实现_Idea

java下使用gRPC的helloworld的demo实现_maven_02

点击下一步,再点击Finsh。

2、配置pom文件,导入grpc的依赖和插件

java下使用gRPC的helloworld的demo实现_Idea_03

全部的pom内容如下:

  1.  
    <?xml version="1.0" encoding="UTF-8"?>
  2.  
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3.  
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4.  
    <modelVersion>4.0.0</modelVersion>
  5.  
     
  6.  
    <groupId>com.grpcprojects</groupId>
  7.  
    <artifactId>grpcExercise3</artifactId>
  8.  
    <version>1.0-SNAPSHOT</version>
  9.  
     
  10.  
    <properties>
  11.  
    <grpc-version>1.20.0</grpc-version>
  12.  
    </properties>
  13.  
     
  14.  
    <dependencies>
  15.  
    <dependency>
  16.  
    <groupId>io.grpc</groupId>
  17.  
    <artifactId>grpc-core</artifactId>
  18.  
    <version>${grpc-version}</version>
  19.  
    </dependency>
  20.  
    <dependency>
  21.  
    <groupId>io.grpc</groupId>
  22.  
    <artifactId>grpc-netty-shaded</artifactId>
  23.  
    <version>${grpc-version}</version>
  24.  
    </dependency>
  25.  
    <dependency>
  26.  
    <groupId>io.grpc</groupId>
  27.  
    <artifactId>grpc-protobuf</artifactId>
  28.  
    <version>${grpc-version}</version>
  29.  
    </dependency>
  30.  
    <dependency>
  31.  
    <groupId>io.grpc</groupId>
  32.  
    <artifactId>grpc-stub</artifactId>
  33.  
    <version>${grpc-version}</version>
  34.  
    </dependency>
  35.  
    </dependencies>
  36.  
     
  37.  
    <build>
  38.  
    <extensions>
  39.  
    <extension>
  40.  
    <groupId>kr.motd.maven</groupId>
  41.  
    <artifactId>os-maven-plugin</artifactId>
  42.  
    <version>1.5.0.Final</version>
  43.  
    </extension>
  44.  
    </extensions>
  45.  
     
  46.  
    <plugins>
  47.  
    <plugin>
  48.  
    <groupId>org.xolstice.maven.plugins</groupId>
  49.  
    <artifactId>protobuf-maven-plugin</artifactId>
  50.  
    <version>0.5.1</version>
  51.  
    <configuration>
  52.  
    <protocArtifact>com.google.protobuf:protoc:3.7.1:exe:${os.detected.classifier}</protocArtifact>
  53.  
    <pluginId>grpc-java</pluginId>
  54.  
    <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.9.1:exe:${os.detected.classifier}</pluginArtifact>
  55.  
    <protoSourceRoot>src/main/proto</protoSourceRoot>
  56.  
    </configuration>
  57.  
    <executions>
  58.  
    <execution>
  59.  
    <goals>
  60.  
    <goal>compile</goal>
  61.  
    <goal>compile-custom</goal>
  62.  
    </goals>
  63.  
    </execution>
  64.  
    </executions>
  65.  
    </plugin>
  66.  
    <plugin>
  67.  
    <groupId>org.apache.maven.plugins</groupId>
  68.  
    <artifactId>maven-compiler-plugin</artifactId>
  69.  
    <version>3.6.1</version>
  70.  
    <configuration>
  71.  
    <source>1.8</source>
  72.  
    <target>1.8</target>
  73.  
    </configuration>
  74.  
    </plugin>
  75.  
    </plugins>
  76.  
    </build>
  77.  
     
  78.  
    </project>

添加好依赖之后的显示:

添加之后选择右下键出现的import change,就能在Maven Projects中看到添加的依赖了。

java下使用gRPC的helloworld的demo实现_gRPC_04

java下使用gRPC的helloworld的demo实现_gRPC_05

3、编写helloworld.proto文件

在项目main目录下新建一个proto文件夹,再在此文件夹下创建一个helloworld.proto文件

java下使用gRPC的helloworld的demo实现_Idea_06

helloworld.proto(跟官网上的一样)中的代码如下:

  1.  
    syntax = "proto3";
  2.  
     
  3.  
    option java_multiple_files = true;
  4.  
    option java_package = "io.grpc.examples.helloworld";
  5.  
    option java_outer_classname = "HelloWorldProto";
  6.  
    option objc_class_prefix = "HLW";
  7.  
     
  8.  
    package helloworld;
  9.  
     
  10.  
    // The greeting service definition.
  11.  
    service Greeter {
  12.  
    // Sends a greeting
  13.  
    rpc SayHello (HelloRequest) returns (HelloReply) {}
  14.  
    }
  15.  
     
  16.  
    // The request message containing the user's name.
  17.  
    message HelloRequest {
  18.  
    string name = 1;
  19.  
    }
  20.  
     
  21.  
    // The response message containing the greetings
  22.  
    message HelloReply {
  23.  
    string message = 1;
  24.  
    }

重要的地方来了,编译helloworld.proto文件,编译此文件有两种方法,第一种使用protoc.exe和protoc-gen-grpc-java插件进行编译。第二种方法是用刚才在项目里边添加的插件进行编译。下边分别进行说明:

第一种:使用protoc.exe和protoc-gen-grpc-java插件进行编译

下载protoc.exe 工具 , 下载地址:https://github.com/protocolbuffers/protobuf/releases

 下载protoc-gen-grpc 插件  , 下载地址: http://jcenter.bintray.com/io/grpc/protoc-gen-grpc-java/

将protoc.exe和protoc-gen-grpc插件放到main目录中:

java下使用gRPC的helloworld的demo实现_Idea_07

 

在项目的terminal窗口中执行如下两条指令:

java下使用gRPC的helloworld的demo实现_java_08

执行完每条指令之后,窗口应该不会出现任何信息,在项目文件目录中会添加如下文件:

java下使用gRPC的helloworld的demo实现_maven_09

第二种方法:用刚才在项目里边添加的插件进行编译

在分割线下边

 

4、添加客户端和服务端代码

我是直接从官网上直接拿过来的代码,分别为HelloWorldClient.java和HelloWorldServer.java

HelloWorldClient.java代码如下:

  1.  
    /*
  2.  
    * Copyright 2015 The gRPC Authors
  3.  
    *
  4.  
    * Licensed under the Apache License, Version 2.0 (the "License");
  5.  
    * you may not use this file except in compliance with the License.
  6.  
    * You may obtain a copy of the License at
  7.  
    *
  8.  
    * http://www.apache.org/licenses/LICENSE-2.0
  9.  
    *
  10.  
    * Unless required by applicable law or agreed to in writing, software
  11.  
    * distributed under the License is distributed on an "AS IS" BASIS,
  12.  
    * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13.  
    * See the License for the specific language governing permissions and
  14.  
    * limitations under the License.
  15.  
    */
  16.  
     
  17.  
    package helloworld;
  18.  
     
  19.  
    import io.grpc.ManagedChannel;
  20.  
    import io.grpc.ManagedChannelBuilder;
  21.  
    import io.grpc.StatusRuntimeException;
  22.  
    import io.grpc.examples.helloworld.GreeterGrpc;
  23.  
    import io.grpc.examples.helloworld.HelloReply;
  24.  
    import io.grpc.examples.helloworld.HelloRequest;
  25.  
     
  26.  
    import java.util.concurrent.TimeUnit;
  27.  
    import java.util.logging.Level;
  28.  
    import java.util.logging.Logger;
  29.  
     
  30.  
    /**
  31.  
    * A simple client that requests a greeting from the {@link HelloWorldServer}.
  32.  
    */
  33.  
    public class HelloWorldClient {
  34.  
    private static final Logger logger = Logger.getLogger(HelloWorldClient.class.getName());
  35.  
     
  36.  
    private final ManagedChannel channel;
  37.  
    private final GreeterGrpc.GreeterBlockingStub blockingStub;
  38.  
     
  39.  
    /** Construct client connecting to HelloWorld server at {@code host:port}. */
  40.  
    public HelloWorldClient(String host, int port) {
  41.  
    this(ManagedChannelBuilder.forAddress(host, port)
  42.  
    // Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
  43.  
    // needing certificates.
  44.  
    .usePlaintext()
  45.  
    .build());
  46.  
    }
  47.  
     
  48.  
    /** Construct client for accessing HelloWorld server using the existing channel. */
  49.  
    HelloWorldClient(ManagedChannel channel) {
  50.  
    this.channel = channel;
  51.  
    blockingStub = GreeterGrpc.newBlockingStub(channel);
  52.  
    }
  53.  
     
  54.  
    public void shutdown() throws InterruptedException {
  55.  
    channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
  56.  
    }
  57.  
     
  58.  
    /** Say hello to server. */
  59.  
    public void greet(String name) {
  60.  
    logger.info("Will try to greet " + name + " ...");
  61.  
    HelloRequest request = HelloRequest.newBuilder().setName(name).build();
  62.  
    HelloReply response;
  63.  
    try {
  64.  
    response = blockingStub.sayHello(request);
  65.  
    } catch (StatusRuntimeException e) {
  66.  
    logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
  67.  
    return;
  68.  
    }
  69.  
    logger.info("Greeting: " + response.getMessage());
  70.  
    }
  71.  
     
  72.  
    /**
  73.  
    * Greet server. If provided, the first element of {@code args} is the name to use in the
  74.  
    * greeting.
  75.  
    */
  76.  
    public static void main(String[] args) throws Exception {
  77.  
    HelloWorldClient client = new HelloWorldClient("localhost", 50051);
  78.  
    try {
  79.  
    /* Access a service running on the local machine on port 50051 */
  80.  
    String user = "world";
  81.  
    if (args.length > 0) {
  82.  
    user = args[0]; /* Use the arg as the name to greet if provided */
  83.  
    }
  84.  
    client.greet(user);
  85.  
    } finally {
  86.  
    client.shutdown();
  87.  
    }
  88.  
    }
  89.  
    }

HelloWorldServer.java代码如下:

  1.  
    /*
  2.  
    * Copyright 2015 The gRPC Authors
  3.  
    *
  4.  
    * Licensed under the Apache License, Version 2.0 (the "License");
  5.  
    * you may not use this file except in compliance with the License.
  6.  
    * You may obtain a copy of the License at
  7.  
    *
  8.  
    * http://www.apache.org/licenses/LICENSE-2.0
  9.  
    *
  10.  
    * Unless required by applicable law or agreed to in writing, software
  11.  
    * distributed under the License is distributed on an "AS IS" BASIS,
  12.  
    * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13.  
    * See the License for the specific language governing permissions and
  14.  
    * limitations under the License.
  15.  
    */
  16.  
     
  17.  
    package helloworld;
  18.  
     
  19.  
    import io.grpc.Server;
  20.  
    import io.grpc.ServerBuilder;
  21.  
    import io.grpc.examples.helloworld.GreeterGrpc;
  22.  
    import io.grpc.examples.helloworld.HelloReply;
  23.  
    import io.grpc.examples.helloworld.HelloRequest;
  24.  
    import io.grpc.stub.StreamObserver;
  25.  
    import java.io.IOException;
  26.  
    import java.util.logging.Logger;
  27.  
     
  28.  
    /**
  29.  
    * Server that manages startup/shutdown of a {@code Greeter} server.
  30.  
    */
  31.  
    public class HelloWorldServer {
  32.  
    private static final Logger logger = Logger.getLogger(HelloWorldServer.class.getName());
  33.  
     
  34.  
    private Server server;
  35.  
     
  36.  
    private void start() throws IOException {
  37.  
    /* The port on which the server should run */
  38.  
    int port = 50051;
  39.  
    server = ServerBuilder.forPort(port)
  40.  
    .addService(new GreeterImpl())
  41.  
    .build()
  42.  
    .start();
  43.  
    logger.info("Server started, listening on " + port);
  44.  
    Runtime.getRuntime().addShutdownHook(new Thread() {
  45.  
    @Override
  46.  
    public void run() {
  47.  
    // Use stderr here since the logger may have been reset by its JVM shutdown hook.
  48.  
    System.err.println("*** shutting down gRPC server since JVM is shutting down");
  49.  
    HelloWorldServer.this.stop();
  50.  
    System.err.println("*** server shut down");
  51.  
    }
  52.  
    });
  53.  
    }
  54.  
     
  55.  
    private void stop() {
  56.  
    if (server != null) {
  57.  
    server.shutdown();
  58.  
    }
  59.  
    }
  60.  
     
  61.  
    /**
  62.  
    * Await termination on the main thread since the grpc library uses daemon threads.
  63.  
    */
  64.  
    private void blockUntilShutdown() throws InterruptedException {
  65.  
    if (server != null) {
  66.  
    server.awaitTermination();
  67.  
    }
  68.  
    }
  69.  
     
  70.  
    /**
  71.  
    * Main launches the server from the command line.
  72.  
    */
  73.  
    public static void main(String[] args) throws IOException, InterruptedException {
  74.  
    final HelloWorldServer server = new HelloWorldServer();
  75.  
    server.start();
  76.  
    server.blockUntilShutdown();
  77.  
    }
  78.  
     
  79.  
    static class GreeterImpl extends GreeterGrpc.GreeterImplBase {
  80.  
     
  81.  
    @Override
  82.  
    public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
  83.  
    HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + req.getName()).build();
  84.  
    responseObserver.onNext(reply);
  85.  
    responseObserver.onCompleted();
  86.  
    }
  87.  
    }
  88.  
    }

 

5、最终的文件结构

java下使用gRPC的helloworld的demo实现_gRPC_10

6、执行服务端和客户端代码

先执行HelloWorldServer.java,再HelloWorldClient.java,得如下运行结果,正面我们的gprc通信成功了。

服务端显示如下:

java下使用gRPC的helloworld的demo实现_maven_11

 

客户端显示如下:

java下使用gRPC的helloworld的demo实现_gRPC_12



步骤1,2和上边完全相同,此处从步骤3的第二种方法开始说。

第二种方法:用刚才在项目里边添加的插件进行编译。

  • 右击Maven.Projects\protobuf\protobuf:compile ,选择run,生成用于序列化的java文件。
  • 再右击Maven.Projects\protobuf\protobuf:compile-custom,选择run,生成用于rpc的java代码。

java下使用gRPC的helloworld的demo实现_gRPC_13

java下使用gRPC的helloworld的demo实现_gRPC_14

执行完这两步,会产生的文件为:

java下使用gRPC的helloworld的demo实现_java_15

但是在执行这两步的过程中,控制台会出现报错的信息,但是在后边服务端和客户端运行的时候并没有报别的错误。

java下使用gRPC的helloworld的demo实现_maven_16

哪位大佬能解决这个问题,麻烦请告知一下,多谢了。

4、客户端和服务端的代码和上边写的一样

5、项目文件目录如下:

java下使用gRPC的helloworld的demo实现_java_17

6、最后的运行结果(和上边的运行结果一样,并没有报错误)

服务端的显示:

java下使用gRPC的helloworld的demo实现_java_18

客户端的显示:

java下使用gRPC的helloworld的demo实现_Idea_19