java下使用gRPC的helloworld的demo實現
參考:
- 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
- grpc官方文件中文版http://doc.oschina.net/grpc?t=58008
- 示例:https://github.com/grpc/grpc-java/tree/master/examples/src/main/java/io/grpc/examples
具體實施步驟:
1、新建一個普通的Maven專案:
點選下一步,再點選Finsh。
2、配置pom檔案,匯入grpc的依賴和外掛
全部的pom內容如下:
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>com.grpcprojects</groupId>
- <artifactId>grpcExercise3</artifactId>
- <version>1.0-SNAPSHOT</version>
- <properties>
- <grpc-version>1.20.0</grpc-version>
-
</properties>
- <dependencies>
- <dependency>
- <groupId>io.grpc</groupId>
- <artifactId>grpc-core</artifactId>
- <version>${grpc-version}</version>
- </dependency>
- <dependency>
- <groupId>io.grpc</groupId>
- <artifactId>grpc-netty-shaded</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>
- <build>
- <extensions>
- <extension>
- <groupId>kr.motd.maven</groupId>
- <artifactId>os-maven-plugin</artifactId>
- <version>1.5.0.Final</version>
- </extension>
- </extensions>
- <plugins>
- <plugin>
- <groupId>org.xolstice.maven.plugins</groupId>
- <artifactId>protobuf-maven-plugin</artifactId>
- <version>0.5.1</version>
- <configuration>
- <protocArtifact>com.google.protobuf:protoc:3.7.1:exe:${os.detected.classifier}</protocArtifact>
- <pluginId>grpc-java</pluginId>
- <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.9.1:exe:${os.detected.classifier}</pluginArtifact>
- <protoSourceRoot>src/main/proto</protoSourceRoot>
- </configuration>
- <executions>
- <execution>
- <goals>
- <goal>compile</goal>
- <goal>compile-custom</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-compiler-plugin</artifactId>
- <version>3.6.1</version>
- <configuration>
- <source>1.8</source>
- <target>1.8</target>
- </configuration>
- </plugin>
- </plugins>
- </build>
- </project>
新增好依賴之後的顯示:
新增之後選擇右下鍵出現的import change,就能在Maven Projects中看到新增的依賴了。
3、編寫helloworld.proto檔案
在專案main目錄下新建一個proto資料夾,再在此資料夾下建立一個helloworld.proto檔案
helloworld.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;
- }
重要的地方來了,編譯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程式碼如下:
- /*
- * Copyright 2015 The gRPC Authors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- package helloworld;
- import io.grpc.ManagedChannel;
- import io.grpc.ManagedChannelBuilder;
- import io.grpc.StatusRuntimeException;
- import io.grpc.examples.helloworld.GreeterGrpc;
- import io.grpc.examples.helloworld.HelloReply;
- import io.grpc.examples.helloworld.HelloRequest;
- import java.util.concurrent.TimeUnit;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- /**
- * A simple client that requests a greeting from the {@link HelloWorldServer}.
- */
- public class HelloWorldClient {
- private static final Logger logger = Logger.getLogger(HelloWorldClient.class.getName());
- private final ManagedChannel channel;
- private final GreeterGrpc.GreeterBlockingStub blockingStub;
- /** Construct client connecting to HelloWorld server at {
- public HelloWorldClient(String host, int port) {
- this(ManagedChannelBuilder.forAddress(host, port)
- // Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
- // needing certificates.
- .usePlaintext()
- .build());
- }
- /** Construct client for accessing HelloWorld server using the existing channel. */
- HelloWorldClient(ManagedChannel channel) {
- this.channel = channel;
- blockingStub = GreeterGrpc.newBlockingStub(channel);
- }
- public void shutdown() throws InterruptedException {
- channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
- }
- /** Say hello to server. */
- public void greet(String name) {
- logger.info("Will try to greet " + name + " ...");
- HelloRequest request = HelloRequest.newBuilder().setName(name).build();
- HelloReply response;
- try {
- response = blockingStub.sayHello(request);
- } catch (StatusRuntimeException e) {
- logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
- return;
- }
- logger.info("Greeting: " + response.getMessage());
- }
- /**
- * Greet server. If provided, the first element of {@code args} is the name to use in the
- * greeting.
- */
- public static void main(String[] args) throws Exception {
- HelloWorldClient client = new HelloWorldClient("localhost", 50051);
- try {
- /* Access a service running on the local machine on port 50051 */
- String user = "world";
- if (args.length > 0) {
- user = args[0]; /* Use the arg as the name to greet if provided */
- }
- client.greet(user);
- } finally {
- client.shutdown();
- }
- }
- }
HelloWorldServer.java程式碼如下:
- /*
- * Copyright 2015 The gRPC Authors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- package helloworld;
- import io.grpc.Server;
- import io.grpc.ServerBuilder;
- import io.grpc.examples.helloworld.GreeterGrpc;
- import io.grpc.examples.helloworld.HelloReply;
- import io.grpc.examples.helloworld.HelloRequest;
- import io.grpc.stub.StreamObserver;
- import java.io.IOException;
- import java.util.logging.Logger;
- /**
- * Server that manages startup/shutdown of a {@code Greeter} server.
- */
- public class HelloWorldServer {
- private static final Logger logger = Logger.getLogger(HelloWorldServer.class.getName());
- 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() {
- 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");
- HelloWorldServer.this.stop();
- System.err.println("*** server shut down");
- }
- });
- }
- private void stop() {
- if (server != null) {
- server.shutdown();
- }
- }
- /**
- * 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();
- }
- static class GreeterImpl extends GreeterGrpc.GreeterImplBase {
- public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
- HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + req.getName()).build();
- responseObserver.onNext(reply);
- responseObserver.onCompleted();
- }
- }
- }
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、最後的執行結果(和上邊的執行結果一樣,並沒有報錯誤)
服務端的顯示:
客戶端的顯示: