快速入门
本指南通过一个简单的示例向您介绍如何在 Kotlin 中使用 gRPC。
快速入门
先决条件
获取示例代码
示例代码位于 grpc-kotlin 仓库中。
将仓库下载为 zip 文件并解压,或克隆仓库
git clone --depth 1 https://github.com/grpc/grpc-kotlin
切换到 examples 目录
cd grpc-kotlin/examples
运行示例
在 examples
目录下
编译客户端和服务器
./gradlew installDist
运行服务器
./server/build/install/server/bin/hello-world-server Server started, listening on 50051
在另一个终端中,运行客户端
./client/build/install/client/bin/hello-world-client Received: Hello world
恭喜!您刚刚运行了一个使用 gRPC 的客户端-服务器应用程序。
更新 gRPC 服务
在本节中,您将通过额外添加一个服务器方法来更新应用程序。该应用程序的 gRPC 服务名为 Greeter
,使用 protocol buffers 定义。要了解如何在 .proto
文件中定义服务,请参阅基础教程。现在,您只需要知道服务器和客户端 stub 都有一个 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;
}
打开 protos/src/main/proto/io/grpc/examples 文件夹中的 helloworld/hello_world.proto
文件,并添加一个新的 SayHelloAgain()
方法,使用相同的请求和响应类型
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
// Sends another greeting
rpc SayHelloAgain (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;
}
记得保存文件!
更新应用程序
当您构建示例时,构建过程会重新生成 HelloWorldProtoGrpcKt.kt
文件,其中包含生成的 gRPC 客户端和服务端类。这也会重新生成用于填充、序列化和检索我们的请求和响应类型的类。
然而,您仍然需要在示例应用程序的手写部分中实现和调用新方法。
更新服务器
打开 server/src/main/kotlin/io/grpc/examples 文件夹中的 helloworld/HelloWorldServer.kt
文件。像这样实现新方法
private class HelloWorldService : GreeterGrpcKt.GreeterCoroutineImplBase() {
override suspend fun sayHello(request: HelloRequest) = helloReply {
message = "Hello ${request.name}"
}
override suspend fun sayHelloAgain(request: HelloRequest) = helloReply {
message = "Hello again ${request.name}"
}
}
更新客户端
打开 client/src/main/kotlin/io/grpc/examples 文件夹中的 helloworld/HelloWorldClient.kt
文件。像这样调用新方法
class HelloWorldClient(
private val channel: ManagedChannel
) : Closeable {
private val stub: GreeterCoroutineStub = GreeterCoroutineStub(channel)
suspend fun greet(name: String) {
val request = helloRequest { this.name = name }
val response = stub.sayHello(request)
println("Received: ${response.message}")
val againResponse = stub.sayHelloAgain(request)
println("Received: ${againResponse.message}")
}
override fun close() {
channel.shutdown().awaitTermination(5, TimeUnit.SECONDS)
}
}
运行更新后的应用程序
像之前一样运行客户端和服务器。在 examples
目录下执行以下命令
编译客户端和服务器
./gradlew installDist
运行服务器
./server/build/install/server/bin/hello-world-server Server started, listening on 50051
在另一个终端中,运行客户端。这次,添加一个名字作为命令行参数
./client/build/install/client/bin/hello-world-client Alice Received: Hello Alice Received: Hello again Alice