gRPC (五)kotlin gRPC样例

举报
张俭 发表于 2023/12/29 17:55:20 2023/12/29
【摘要】 本文代码地址https://gitee.com/shoothzj/grpc-examples kotlin实现gRPC客户端服务端 添加依赖import com.google.protobuf.gradle.generateProtoTasksimport com.google.protobuf.gradle.idimport com.google.protobuf.gradle.plug...

本文代码地址

https://gitee.com/shoothzj/grpc-examples

kotlin实现gRPC客户端服务端

添加依赖

import com.google.protobuf.gradle.generateProtoTasks
import com.google.protobuf.gradle.id
import com.google.protobuf.gradle.plugins
import com.google.protobuf.gradle.protobuf
import com.google.protobuf.gradle.protoc
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
    kotlin("jvm") version "1.7.10"
    id("com.google.protobuf") version "0.8.19"
    id("java")
}

group = "com.github.shoothzj"
version = "1.0-SNAPSHOT"

repositories {
    mavenCentral()
}

ext["grpcVersion"] = "1.47.0"
ext["protobufVersion"] = "3.21.2"
ext["grpcKotlinVersion"] = "1.3.0"

dependencies {
    api("io.grpc:grpc-netty:${rootProject.ext["grpcVersion"]}")
    api("io.grpc:grpc-stub:${rootProject.ext["grpcVersion"]}")
    api("io.grpc:grpc-protobuf:${rootProject.ext["grpcVersion"]}")
    api("com.google.protobuf:protobuf-java-util:${rootProject.ext["protobufVersion"]}")
    api("com.google.protobuf:protobuf-kotlin:${rootProject.ext["protobufVersion"]}")
    api("io.grpc:grpc-kotlin-stub:${rootProject.ext["grpcKotlinVersion"]}")
    testImplementation(kotlin("test"))
}

protobuf {
    protoc {
        artifact = "com.google.protobuf:protoc:${rootProject.ext["protobufVersion"]}"
    }
    plugins {
        id("grpc") {
            artifact = "io.grpc:protoc-gen-grpc-java:${rootProject.ext["grpcVersion"]}"
        }
        id("grpckt") {
            artifact = "io.grpc:protoc-gen-grpc-kotlin:${rootProject.ext["grpcKotlinVersion"]}:jdk8@jar"
        }
    }
    generateProtoTasks {
        all().forEach {
            it.plugins {
                id("grpc")
                id("grpckt")
            }
            it.builtins {
                id("kotlin")
            }
        }
    }
}

tasks.test {
    useJUnitPlatform()
}

tasks.withType<KotlinCompile> {
    kotlinOptions.jvmTarget = "1.8"
}

书写proto文件

proto文件就用上述的定义,放置在src/main/proto文件夹下,如下图

image.png

server侧代码

package com.github.shoothzj.grpc

import com.github.shoothzj.grpc.example.EchoProto2ServiceGrpcKt
import com.github.shoothzj.grpc.example.MessageProto2
import io.grpc.Server
import io.grpc.ServerBuilder

class EchoServer(private val port: Int) {
    val server: Server = ServerBuilder
        .forPort(port)
        .addService(EchoService())
        .build()

    fun start() {
        server.start()
        println("Server started, listening on $port")
        Runtime.getRuntime().addShutdownHook(
            Thread {
                println("*** shutting down gRPC server since JVM is shutting down")
                this@EchoServer.stop()
                println("*** server shut down")
            }
        )
    }

    private fun stop() {
        server.shutdown()
    }

    fun blockUntilShutdown() {
        server.awaitTermination()
    }

    internal class EchoService : EchoProto2ServiceGrpcKt.EchoProto2ServiceCoroutineImplBase() {
        override suspend fun echoProto2(request: MessageProto2.EchoProto2Req): MessageProto2.EchoProto2Resp {
            return MessageProto2.EchoProto2Resp.newBuilder()
                .setStrReq(request.strReq)
                .setStrOpt(request.strOpt)
                .addAllStrRep(request.strRepList)
                .setInt64Req(request.int64Req)
                .setInt32Opt(request.int32Opt)
                .setComic(request.comic)
                .build()
        }
    }
}

fun main() {
    val port = System.getenv("PORT")?.toInt() ?: 10240
    val server = EchoServer(port)
    server.start()
    server.blockUntilShutdown()
}

client侧代码

package com.github.shoothzj.grpc

import com.github.shoothzj.grpc.example.EchoProto2ServiceGrpcKt
import com.github.shoothzj.grpc.example.MessageProto2
import io.grpc.ManagedChannel
import io.grpc.ManagedChannelBuilder
import java.io.Closeable
import java.util.concurrent.TimeUnit

class EchoClient(private val channel: ManagedChannel) : Closeable {
    private val stub: EchoProto2ServiceGrpcKt.EchoProto2ServiceCoroutineStub = EchoProto2ServiceGrpcKt.EchoProto2ServiceCoroutineStub(channel)

    suspend fun greet() {
        val request = MessageProto2.EchoProto2Req.newBuilder()
            .setStrReq("strReq")
            .setStrOpt("strOpt")
            .addAllStrRep(listOf("str", "rep"))
            .setInt64Req(1)
            .setInt32Opt(2)
            .setComic(MessageProto2.Comic.Bleach)
            .build()
        val response = stub.echoProto2(request)
        println("Received: $response")
    }

    override fun close() {
        channel.shutdown().awaitTermination(5, TimeUnit.SECONDS)
    }
}

suspend fun main(args: Array<String>) {
    val port = 10240

    val channel = ManagedChannelBuilder.forAddress("localhost", port).usePlaintext().build()

    val client = EchoClient(channel)

    val user = args.singleOrNull() ?: "world"
    client.greet()
}
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。