1. 程式人生 > 其它 >java下使用gRPC的helloworld的demo實現

java下使用gRPC的helloworld的demo實現

參考:

  1. java下使用gRPC的helloworld的demo實現https://blog.csdn.net/u013992365/article/details/81698531#%E6%96%B0%E5%BB%BA%E4%B8%80%E4%B8%AA%E6%99%AE%E9%80%9A%E7%9A%84maven%E9%A1%B9%E7%9B%AE
  2. grpc官方文件中文版http://doc.oschina.net/grpc?t=58008
  3. 示例:https://github.com/grpc/grpc-java/tree/master/examples/src/main/java/io/grpc/examples

具體實施步驟:

1、新建一個普通的Maven專案:

點選下一步,再點選Finsh。

2、配置pom檔案,匯入grpc的依賴和外掛

全部的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. <groupId>com.grpcprojects</groupId>
  6. <artifactId>grpcExercise3</artifactId>
  7. <version>1.0-SNAPSHOT</version>
  8. <properties>
  9. <grpc-version>1.20.0</grpc-version>
  10. </properties>
  11. <dependencies>
  12. <dependency>
  13. <groupId>io.grpc</groupId>
  14. <artifactId>grpc-core</artifactId>
  15. <version>${grpc-version}</version>
  16. </dependency>
  17. <dependency>
  18. <groupId>io.grpc</groupId>
  19. <artifactId>grpc-netty-shaded</artifactId>
  20. <version>${grpc-version}</version>
  21. </dependency>
  22. <dependency>
  23. <groupId>io.grpc</groupId>
  24. <artifactId>grpc-protobuf</artifactId>
  25. <version>${grpc-version}</version>
  26. </dependency>
  27. <dependency>
  28. <groupId>io.grpc</groupId>
  29. <artifactId>grpc-stub</artifactId>
  30. <version>${grpc-version}</version>
  31. </dependency>
  32. </dependencies>
  33. <build>
  34. <extensions>
  35. <extension>
  36. <groupId>kr.motd.maven</groupId>
  37. <artifactId>os-maven-plugin</artifactId>
  38. <version>1.5.0.Final</version>
  39. </extension>
  40. </extensions>
  41. <plugins>
  42. <plugin>
  43. <groupId>org.xolstice.maven.plugins</groupId>
  44. <artifactId>protobuf-maven-plugin</artifactId>
  45. <version>0.5.1</version>
  46. <configuration>
  47. <protocArtifact>com.google.protobuf:protoc:3.7.1:exe:${os.detected.classifier}</protocArtifact>
  48. <pluginId>grpc-java</pluginId>
  49. <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.9.1:exe:${os.detected.classifier}</pluginArtifact>
  50. <protoSourceRoot>src/main/proto</protoSourceRoot>
  51. </configuration>
  52. <executions>
  53. <execution>
  54. <goals>
  55. <goal>compile</goal>
  56. <goal>compile-custom</goal>
  57. </goals>
  58. </execution>
  59. </executions>
  60. </plugin>
  61. <plugin>
  62. <groupId>org.apache.maven.plugins</groupId>
  63. <artifactId>maven-compiler-plugin</artifactId>
  64. <version>3.6.1</version>
  65. <configuration>
  66. <source>1.8</source>
  67. <target>1.8</target>
  68. </configuration>
  69. </plugin>
  70. </plugins>
  71. </build>
  72. </project>

新增好依賴之後的顯示:

新增之後選擇右下鍵出現的import change,就能在Maven Projects中看到新增的依賴了。

3、編寫helloworld.proto檔案

在專案main目錄下新建一個proto資料夾,再在此資料夾下建立一個helloworld.proto檔案

helloworld.proto(跟官網上的一樣)中的程式碼如下:

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

重要的地方來了,編譯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目錄中:

在專案的terminal視窗中執行如下兩條指令:

執行完每條指令之後,視窗應該不會出現任何資訊,在專案檔案目錄中會新增如下檔案:

第二種方法:用剛才在專案裡邊新增的外掛進行編譯

在分割線下邊

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. package helloworld;
  17. import io.grpc.ManagedChannel;
  18. import io.grpc.ManagedChannelBuilder;
  19. import io.grpc.StatusRuntimeException;
  20. import io.grpc.examples.helloworld.GreeterGrpc;
  21. import io.grpc.examples.helloworld.HelloReply;
  22. import io.grpc.examples.helloworld.HelloRequest;
  23. import java.util.concurrent.TimeUnit;
  24. import java.util.logging.Level;
  25. import java.util.logging.Logger;
  26. /**
  27. * A simple client that requests a greeting from the {@link HelloWorldServer}.
  28. */
  29. public class HelloWorldClient {
  30. private static final Logger logger = Logger.getLogger(HelloWorldClient.class.getName());
  31. private final ManagedChannel channel;
  32. private final GreeterGrpc.GreeterBlockingStub blockingStub;
  33. /** Construct client connecting to HelloWorld server at {@code host:port}. */
  34. public HelloWorldClient(String host, int port) {
  35. this(ManagedChannelBuilder.forAddress(host, port)
  36. // Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
  37. // needing certificates.
  38. .usePlaintext()
  39. .build());
  40. }
  41. /** Construct client for accessing HelloWorld server using the existing channel. */
  42. HelloWorldClient(ManagedChannel channel) {
  43. this.channel = channel;
  44. blockingStub = GreeterGrpc.newBlockingStub(channel);
  45. }
  46. public void shutdown() throws InterruptedException {
  47. channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
  48. }
  49. /** Say hello to server. */
  50. public void greet(String name) {
  51. logger.info("Will try to greet " + name + " ...");
  52. HelloRequest request = HelloRequest.newBuilder().setName(name).build();
  53. HelloReply response;
  54. try {
  55. response = blockingStub.sayHello(request);
  56. } catch (StatusRuntimeException e) {
  57. logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
  58. return;
  59. }
  60. logger.info("Greeting: " + response.getMessage());
  61. }
  62. /**
  63. * Greet server. If provided, the first element of {@code args} is the name to use in the
  64. * greeting.
  65. */
  66. public static void main(String[] args) throws Exception {
  67. HelloWorldClient client = new HelloWorldClient("localhost", 50051);
  68. try {
  69. /* Access a service running on the local machine on port 50051 */
  70. String user = "world";
  71. if (args.length > 0) {
  72. user = args[0]; /* Use the arg as the name to greet if provided */
  73. }
  74. client.greet(user);
  75. } finally {
  76. client.shutdown();
  77. }
  78. }
  79. }

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. package helloworld;
  17. import io.grpc.Server;
  18. import io.grpc.ServerBuilder;
  19. import io.grpc.examples.helloworld.GreeterGrpc;
  20. import io.grpc.examples.helloworld.HelloReply;
  21. import io.grpc.examples.helloworld.HelloRequest;
  22. import io.grpc.stub.StreamObserver;
  23. import java.io.IOException;
  24. import java.util.logging.Logger;
  25. /**
  26. * Server that manages startup/shutdown of a {@code Greeter} server.
  27. */
  28. public class HelloWorldServer {
  29. private static final Logger logger = Logger.getLogger(HelloWorldServer.class.getName());
  30. private Server server;
  31. private void start() throws IOException {
  32. /* The port on which the server should run */
  33. int port = 50051;
  34. server = ServerBuilder.forPort(port)
  35. .addService(new GreeterImpl())
  36. .build()
  37. .start();
  38. logger.info("Server started, listening on " + port);
  39. Runtime.getRuntime().addShutdownHook(new Thread() {
  40. @Override
  41. public void run() {
  42. // Use stderr here since the logger may have been reset by its JVM shutdown hook.
  43. System.err.println("*** shutting down gRPC server since JVM is shutting down");
  44. HelloWorldServer.this.stop();
  45. System.err.println("*** server shut down");
  46. }
  47. });
  48. }
  49. private void stop() {
  50. if (server != null) {
  51. server.shutdown();
  52. }
  53. }
  54. /**
  55. * Await termination on the main thread since the grpc library uses daemon threads.
  56. */
  57. private void blockUntilShutdown() throws InterruptedException {
  58. if (server != null) {
  59. server.awaitTermination();
  60. }
  61. }
  62. /**
  63. * Main launches the server from the command line.
  64. */
  65. public static void main(String[] args) throws IOException, InterruptedException {
  66. final HelloWorldServer server = new HelloWorldServer();
  67. server.start();
  68. server.blockUntilShutdown();
  69. }
  70. static class GreeterImpl extends GreeterGrpc.GreeterImplBase {
  71. @Override
  72. public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
  73. HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + req.getName()).build();
  74. responseObserver.onNext(reply);
  75. responseObserver.onCompleted();
  76. }
  77. }
  78. }

5、最終的檔案結構

6、執行服務端和客戶端程式碼

先執行HelloWorldServer.java,再HelloWorldClient.java,得如下執行結果,正面我們的gprc通訊成功了。

服務端顯示如下:

客戶端顯示如下:



步驟1,2和上邊完全相同,此處從步驟3的第二種方法開始說。

第二種方法:用剛才在專案裡邊新增的外掛進行編譯。

  • 右擊Maven.Projects\protobuf\protobuf:compile,選擇run,生成用於序列化的java檔案。
  • 再右擊Maven.Projects\protobuf\protobuf:compile-custom,選擇run,生成用於rpc的java程式碼。

執行完這兩步,會產生的檔案為:

但是在執行這兩步的過程中,控制檯會出現報錯的資訊,但是在後邊服務端和客戶端執行的時候並沒有報別的錯誤。

哪位大佬能解決這個問題,麻煩請告知一下,多謝了。

4、客戶端和服務端的程式碼和上邊寫的一樣

5、專案檔案目錄如下:

6、最後的執行結果(和上邊的執行結果一樣,並沒有報錯誤)

服務端的顯示:

客戶端的顯示: