Kotlin的gRPC:库与使用示例
gRPC是一个由Google开发的高性能远程过程调用(RPC)框架。它使用Protocol Buffers(protobuf)进行数据序列化,并使用HTTP/2进行传输。在Kotlin生态系统中,得益于支持协程和强类型化的库,gRPC的集成尤为顺畅。本文将介绍在Kotlin中使用gRPC所需的主要工具,并提供服务器和客户端的实际示例。
主要库
要在Kotlin中使用gRPC,需要以下技术栈:
- grpc-kotlin — Google官方库,提供Kotlin特有的API,包括对协程(suspend函数、Flow)的支持。
- protobuf-java 和 protobuf-gradle-plugin — 用于从.proto文件生成类。
- grpc-netty 或 grpc-okhttp — 传输层(服务器使用Netty,Android/客户端使用OkHttp)。
- javax.annotation-api — 通常需要用于正确编译生成的代码。
使用Gradle(Kotlin DSL)管理依赖项。dependencies块示例:
dependencies { implementation("io.grpc:grpc-netty-shaded:1.58.0") implementation("io.grpc:grpc-protobuf:1.58.0") implementation("io.grpc:grpc-stub:1.58.0") implementation("io.grpc:grpc-kotlin-stub:1.4.0") implementation("com.google.protobuf:protobuf-java:3.24.3") implementation("javax.annotation:javax.annotation-api:1.3.2")}同时,务必添加protobuf插件以生成代码:
plugins { id("com.google.protobuf") version "0.9.4"}
protobuf { protoc { artifact = "com.google.protobuf:protoc:3.24.3" } plugins { create("grpc") { artifact = "io.grpc:protoc-gen-grpc-java:1.58.0" } create("grpckt") { artifact = "io.grpc:protoc-gen-grpc-kotlin:1.4.0:jdk8@jar" } } generateProtoTasks { all().forEach { it.plugins { create("grpc") create("grpckt") } } }}通过.proto文件定义服务
创建文件 src/main/proto/hello.proto:
syntax = "proto3";
package com.example.grpc;
service Greeter { rpc SayHello (HelloRequest) returns (HelloReply);}
message HelloRequest { string name = 1;}
message HelloReply { string message = 1;}运行Gradle构建后,将生成以下类:HelloRequest、HelloReply、GreeterGrpc 和 GreeterGrpcKt(支持协程的Kotlin版本)。
在Kotlin中实现gRPC服务器
服务器将使用生成的类 GreeterGrpcKt.GreeterCoroutineImplBase:
import com.example.grpc.GreeterGrpcKtimport com.example.grpc.HelloReplyimport com.example.grpc.HelloRequestimport io.grpc.ServerBuilderimport kotlinx.coroutines.runBlocking
class GreeterService : GreeterGrpcKt.GreeterCoroutineImplBase() { override suspend fun sayHello(request: HelloRequest): HelloReply { val message = "你好,${request.name}!" println("收到请求:${request.name}") return HelloReply.newBuilder().setMessage(message).build() }}
fun main() { val port = 50051 val server = ServerBuilder.forPort(port) .addService(GreeterService()) .build()
server.start() println("服务器已在端口 $port 上启动") server.awaitTermination()}在Kotlin中实现gRPC客户端
客户端使用支持协程的通道和stub:
import com.example.grpc.GreeterGrpcKti