快速入门
本指南通过一个简单的示例,引导您开始在 Java 中使用 gRPC。
快速入门
先决条件
- JDK 7 或更高版本
获取示例代码
示例代码是 grpc-java 代码仓库的一部分。
下载仓库的 zip 文件 并解压,或克隆仓库
git clone -b v1.69.0 --depth 1 https://github.com/grpc/grpc-java
切换到 examples 目录
cd grpc-java/examples
运行示例
从 examples
目录
编译客户端和服务器
./gradlew installDist
运行服务器
./build/install/examples/bin/hello-world-server INFO: Server started, listening on 50051
从另一个终端,运行客户端
./build/install/examples/bin/hello-world-client INFO: Will try to greet world ... INFO: Greeting: Hello world
恭喜!您刚刚使用 gRPC 运行了一个客户端-服务器应用程序。
注意
我们省略了本页显示的客户端和服务器跟踪输出中的时间戳。更新 gRPC 服务
在本节中,您将通过添加一个额外的服务器方法来更新应用程序。gRPC 服务使用 协议缓冲区定义。要了解更多关于如何在 .proto
文件中定义服务的信息,请参阅 基础教程。现在,您只需要知道服务器和客户端存根都有一个 SayHello()
RPC 方法,该方法接收客户端的 HelloRequest
参数并返回服务器的 HelloReply
,并且该方法定义如下:
// 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;
}
打开 src/main/proto/helloworld.proto
并添加一个新的 SayHelloAgain()
方法,该方法与 SayHello()
具有相同的请求和响应类型。
// The greeting service definition.
service Greeter {
// Sends a greeting. Original method.
rpc SayHello (HelloRequest) returns (HelloReply) {}
// Sends another greeting. New method.
rpc SayHelloAgain (HelloRequest) returns (HelloReply) {}
}
// The request message containing the user's name.
message HelloRequest {
// The name of the user.
string name = 1;
}
// The response message containing the greetings
message HelloReply {
// The greeting message.
string message = 1;
}
记得保存文件!
更新应用程序
当您构建示例时,构建过程会重新生成 GreeterGrpc.java
,其中包含生成的 gRPC 客户端和服务器类。这也将重新生成用于填充、序列化和检索我们的请求和响应类型的类。
但是,您仍然需要在示例应用程序的手写部分中实现和调用新方法。
更新服务器
在同一目录下,打开 src/main/java/io/grpc/examples/helloworld/HelloWorldServer.java
。像这样实现新方法:
// Implementation of the gRPC service on the server-side.
private class GreeterImpl extends GreeterGrpc.GreeterImplBase {
@Override
public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
// Generate a greeting message for the original method
HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + req.getName()).build();
// Send the reply back to the client.
responseObserver.onNext(reply);
// Indicate that no further messages will be sent to the client.
responseObserver.onCompleted();
}
@Override
public void sayHelloAgain(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
// Generate another greeting message for the new method.
HelloReply reply = HelloReply.newBuilder().setMessage("Hello again " + req.getName()).build();
// Send the reply back to the client.
responseObserver.onNext(reply);
// Indicate that no further messages will be sent to the client.
responseObserver.onCompleted();
}
}
更新客户端
在同一目录下,打开 src/main/java/io/grpc/examples/helloworld/HelloWorldClient.java
。像这样调用新方法:
// Client-side logic for interacting with the gRPC service.
public void greet(String name) {
// Log a message indicating the intention to greet a user.
logger.info("Will try to greet " + name + " ...");
// Creating a request with the user's name.
HelloRequest request = HelloRequest.newBuilder().setName(name).build();
HelloReply response;
try {
// Call the original method on the server.
response = blockingStub.sayHello(request);
} catch (StatusRuntimeException e) {
// Log a warning if the RPC fails.
logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
return;
}
// Log the response from the original method.
logger.info("Greeting: " + response.getMessage());
try {
// Call the new method on the server.
response = blockingStub.sayHelloAgain(request);
} catch (StatusRuntimeException e) {
// Log a warning if the RPC fails.
logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
return;
}
// Log the response from the new method.
logger.info("Greeting: " + response.getMessage());
}
运行更新后的应用程序
像以前一样运行客户端和服务器。从 examples
目录执行以下命令:
编译客户端和服务器
./gradlew installDist
运行服务器
./build/install/examples/bin/hello-world-server INFO: Server started, listening on 50051
从另一个终端,运行客户端
./build/install/examples/bin/hello-world-client INFO: Will try to greet world ... INFO: Greeting: Hello world INFO: Greeting: Hello again world