SpringBoot+Kotlin中使用GRPC實現(xiàn)服務通信的示例代碼
示例項目見:kotlin-grpc
一、導入依賴:
import com.google.protobuf.gradle.*
plugins {
id("org.springframework.boot") version "2.3.1.RELEASE"
id("io.spring.dependency-management") version "1.0.9.RELEASE"
id("org.asciidoctor.convert") version "1.5.9.2"
kotlin("jvm") version "1.6.0"
kotlin("plugin.spring") version "1.6.0"
id("com.google.protobuf") version "0.9.2"
}
repositories {
mavenCentral()
}
group = "com.whrss.kotlin-grpc"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_1_8
java.targetCompatibility = JavaVersion.VERSION_1_8
sourceSets.main {
java.srcDirs("src/main/kotlin")
}
extra["spring-restdocs.version"] = "2.0.5.BUILD-SNAPSHOT"
val snippetsDir by extra { file("build/generated-snippets") }
dependencies {
implementation("com.google.protobuf:protobuf-java:3.22.2")
implementation("io.grpc:grpc-protobuf:1.53.0")
implementation("com.google.protobuf:protobuf-kotlin:3.22.2")
implementation("io.grpc:grpc-kotlin-stub:1.3.0")
implementation("io.grpc:grpc-netty:1.56.1")
implementation("io.grpc:grpc-all:1.56.1")
}
protobuf {
protoc {
artifact = "com.google.protobuf:protoc:3.19.4"
}
plugins {
id("grpc") {
artifact = "io.grpc:protoc-gen-grpc-java:1.40.1"
}
id("grpckt") {
artifact = "io.grpc:protoc-gen-grpc-kotlin:1.3.0:jdk8@jar"
}
}
// Enable Kotlin generation
generateProtoTasks {
all().forEach {
it.plugins {
id("grpc")
id("grpckt")
}
} }}二、設(shè)置Proto
將 proto 文件放在 src/mian/proto 目錄下
syntax = "proto3";
import "google/api/annotations.proto";
option java_multiple_files = true;
package hello_world.v1;
service HelloWorldService{
rpc GetUserInfo (GetUserRequest) returns (GetUserReply) {
option (google.api.http) = {
get: "/api/v1/users"
};
}
}
message GetUserRequest{
// 用戶showId
string userId = 1;
}
message GetUserReply{
// 用戶showId
string userId = 1;
}執(zhí)行 ./gradlew clean build
build成功則會在 build/generated/source/proto/main 下生成對應的 grpc 、 grpckt 、 java 文件在程序中可以直接導包引入

三、Server端
寫一個 service
import hello_world.v1.GetUserReply
import hello_world.v1.GetUserRequest
import hello_world.v1.HelloWorldServiceGrpcKt
class Service : HelloWorldServiceGrpcKt.HelloWorldServiceCoroutineImplBase() {
override suspend fun getUserInfo(request: GetUserRequest) : GetUserReply {
println("getItemStatistics exec")
return GetUserReply.newBuilder()
.setUserId(request.userId)
.build()
}
}在 main 入口引入啟動
import io.grpc.ServerBuilder
fun main() {
helloServer()
}
fun helloServer() {
val helloService = Service()
val server = ServerBuilder
.forPort(15001)
.addService(helloService)
.build()
Runtime.getRuntime().addShutdownHook(Thread {
server.shutdown()
server.awaitTermination()
})
server.start()
println("server start")
server.awaitTermination()
println("server restart")
}四、Client 端
import hello_world.v1.GetUserRequest
import hello_world.v1.HelloWorldServiceGrpc
import io.grpc.ManagedChannelBuilder
fun main() {
val channel = ManagedChannelBuilder.forAddress("localhost", 15001).usePlaintext()
val stub = HelloWorldServiceGrpc.newBlockingStub(channel.build())
val response = stub.getUserInfo(GetUserRequest.newBuilder().setUserId("0").build())
println(response)
}五、一些坑
io.grpc 和 com.google的一些依賴是有關(guān)聯(lián)的,如果依賴版本之間有巨大差異,是會導致運行錯誤的。比如我之前使用到了一個google的一個特別老的依賴:com.google.code.google-collections:google-collect:snapshot-20080530,導致了我程序運行時提示:
Exception in thread "main" java.lang.NoSuchMethodError: 'void com.google.common.base.Preconditions.checkArgument(boolean, java.lang.String, char, java.lang.Object)'
at io.grpc.Metadata$Key.validateName(Metadata.java:754)
at io.grpc.Metadata$Key.<init>(Metadata.java:762)
at io.grpc.Metadata$Key.<init>(Metadata.java:671)
at io.grpc.Metadata$AsciiKey.<init>(Metadata.java:971)
at io.grpc.Metadata$AsciiKey.<init>(Metadata.java:966)
at io.grpc.Metadata$Key.of(Metadata.java:708)
at io.grpc.Metadata$Key.of(Metadata.java:704)
at io.grpc.internal.GrpcUtil.<clinit>(GrpcUtil.java:99)
at io.grpc.netty.Utils.<clinit>(Utils.java:83)
at io.grpc.netty.UdsNettyChannelProvider.isAvailable(UdsNettyChannelProvider.java:34)
at io.grpc.ManagedChannelRegistry$ManagedChannelPriorityAccessor.isAvailable(ManagedChannelRegistry.java:211)
at io.grpc.ManagedChannelRegistry$ManagedChannelPriorityAccessor.isAvailable(ManagedChannelRegistry.java:207)
at io.grpc.ServiceProviders.loadAll(ServiceProviders.java:68)
at io.grpc.ManagedChannelRegistry.getDefaultRegistry(ManagedChannelRegistry.java:101)
at io.grpc.ManagedChannelProvider.provider(ManagedChannelProvider.java:43)
at io.grpc.ManagedChannelBuilder.forAddress(ManagedChannelBuilder.java:39)
at com.ck567.kotlingrpc.ClientKt.main(Client.kt:9)
at com.ck567.kotlingrpc.ClientKt.main(Client.kt)
在google是發(fā)現(xiàn)不了具體的問題的,可以注意一下。
上面的依賴版本都是基于對應spring boot和 kotlin 版本的,如果你的版本不適配,可能也需要折騰一下,但問題應該不是很大。
到此這篇關(guān)于SpringBoot+Kotlin中使用GRPC實現(xiàn)服務通信的示例代碼的文章就介紹到這了,更多相關(guān)SpringBoot Kotlin GRPC服務通信內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
spring boot actuator監(jiān)控超詳細教程
Spring Boot Actuator就是一款可以幫助你監(jiān)控系統(tǒng)數(shù)據(jù)的框架,其可以監(jiān)控很多很多的系統(tǒng)數(shù)據(jù),接下來通過本文給大家介紹spring boot actuator監(jiān)控超詳細教程,感興趣的朋友一起看看吧2021-10-10
Java面向?qū)ο蠡A(chǔ)知識之委托和lambda
這篇文章主要介紹了Java面向?qū)ο蟮闹泻?lambda,文中有非常詳細的代碼示例,對正在學習java基礎(chǔ)的小伙伴們有很好的幫助,需要的朋友可以參考下2021-11-11
Java?設(shè)計模式以虹貓藍兔的故事講解簡單工廠模式
簡單工廠模式是屬于創(chuàng)建型模式,又叫做靜態(tài)工廠方法(Static Factory Method)模式,但不屬于23種GOF設(shè)計模式之一。簡單工廠模式是由一個工廠對象決定創(chuàng)建出哪一種產(chǎn)品類的實例。簡單工廠模式是工廠模式家族中最簡單實用的模式,可以理解為是不同工廠模式的一個特殊實現(xiàn)2022-03-03
SpringBoot項目使用Log4j2+SLF4J構(gòu)建日志的方法步驟
在現(xiàn)代軟件開發(fā)中,日志記錄是一個重要的部分,Spring Boot配置了多種日志框架,這篇文章主要介紹了SpringBoot項目使用Log4j2+SLF4J構(gòu)建日志的方法步驟,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2025-11-11
springboot項目中jackson-序列化-處理 NULL教程
這篇文章主要介紹了springboot項目中jackson-序列化-處理 NULL教程,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-10-10
Spring 中如何根據(jù)環(huán)境切換配置 @Profile
這篇文章主要介紹了Spring中如何根據(jù)環(huán)境切換配置@Profile的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08

