参考:
- java下使用gRPC的helloworld的demo实现javascript:void(0)
- grpc官方文档中文版 javascript:void(0)
- 示例:https://github.com/grpc/grpc-java/tree/master/examples/src/main/java/io/grpc/examples
具体实施步骤:
1、新建一个普通的Maven项目:
点击下一步,再点击Finsh。
2、配置pom文件,导入grpc的依赖和插件
全部的pom内容如下:
-
<?xml version="1.0" encoding="UTF-8"?>
-
<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 {@code host:port}. */
-
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() {
-
@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");
-
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 {
-
-
@Override
-
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、最后的运行结果(和上边的运行结果一样,并没有报错误)
服务端的显示:
客户端的显示: