SpringBoot+Kotlin中使用GRPC实现服务通信的示例代码

 更新时间:2023年07月11日 14:38:44   作者:了迹奇有没  
本文主要介绍了SpringBoot+Kotlin中使用GRPC实现服务通信的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

示例项目见: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")  
            }  
        }    }}

二、设置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;  
}

执行 ./gradlew clean build

build成功则会在 build/generated/source/proto/main 下生成对应的 grpcgrpcktjava 文件在程序中可以直接导包引入

三、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的一些依赖是有关联的,如果依赖版本之间有巨大差异,是会导致运行错误的。比如我之前使用到了一个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是发现不了具体的问题的,可以注意一下。

上面的依赖版本都是基于对应spring boot和 kotlin 版本的,如果你的版本不适配,可能也需要折腾一下,但问题应该不是很大。

到此这篇关于SpringBoot+Kotlin中使用GRPC实现服务通信的示例代码的文章就介绍到这了,更多相关SpringBoot Kotlin GRPC服务通信内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java通过httpclient比较重定向和请求转发

    Java通过httpclient比较重定向和请求转发

    这篇文章主要介绍了Java通过httpclient比较重定向和请求转发,HttpClient 4.x 版本,get请求方法会自动进行重定向,而post请求方法不会自动进行重定向,需要的朋友可以参考下
    2023-04-04
  • Java处理时间格式CST和GMT转换方法示例

    Java处理时间格式CST和GMT转换方法示例

    这篇文章主要给大家介绍了关于Java处理时间格式CST和GMT转换方法的相关资料,相信很多小伙伴在时间格式转换的时候非常头疼,文中通过代码示例介绍的非常详细,需要的朋友可以参考下
    2023-09-09
  • SpringCloud中的Consul详解

    SpringCloud中的Consul详解

    这篇文章主要介绍了SpringCloud中的Consul知识,本文使用的是docker-compose方式管理consul服务,直接启动即可,需要的朋友可以参考下
    2022-03-03
  • springboot+thymeleaf国际化之LocaleResolver接口的示例

    springboot+thymeleaf国际化之LocaleResolver接口的示例

    本篇文章主要介绍了springboot+thymeleaf国际化之LocaleResolver的示例 ,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-11-11
  • Springboot实现Activemq死信队列详解

    Springboot实现Activemq死信队列详解

    这篇文章主要介绍了Springboot实现Activemq死信队列详解,Activemq服务端配置重新投递次数超过 MaximumRedeliveries ,则会进入死信队列,默认情况,有一个死信队列:AcitveMQ.DLQ,所有的消息都投递到此队列,包括过期消息,重投递失败消息,需要的朋友可以参考下
    2023-12-12
  • 使用Fastjson进行JSON生成与解析的新手指南

    使用Fastjson进行JSON生成与解析的新手指南

    Fastjson是阿里巴巴开源的高性能 JSON 库,适用于 Java 对象的序列化和反序列化,本文将详细介绍一下如何使用Fastjson进行json的生成与解析吧
    2025-04-04
  • java.lang.OutOfMemoryError: Metaspace异常解决的方法

    java.lang.OutOfMemoryError: Metaspace异常解决的方法

    这篇文章主要介绍了java.lang.OutOfMemoryError: Metaspace异常解决的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-03-03
  • Java虚拟机之对象创建过程与类加载机制及双亲委派模型

    Java虚拟机之对象创建过程与类加载机制及双亲委派模型

    这篇文章主要给大家介绍了关于Java虚拟机之对象创建过程与类加载机制及双亲委派模型的相关资料,本文通过示例代码以及图文介绍的非常详细,对大家学习或者使用java具有一定的参考学习价值,需要的朋友可以参考下
    2021-11-11
  • java 获取用户的MAC地址多种方法实例详解

    java 获取用户的MAC地址多种方法实例详解

    这篇文章主要介绍了JAVA实现获取用户的MAC地址的多种方法实例,需要的朋友可以参考下
    2017-04-04
  • Java使用Deque实现堆栈的方法

    Java使用Deque实现堆栈的方法

    这篇文章主要介绍了Java使用Deque实现堆栈的方法,实例分析了java简单实现堆栈的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-07-07

最新评论