[ Kotlin ] Integrate ProtoBuffer and GoogleRPC Into KotlinNative

文章目录

          • [Declare Plugin and Repository](#Declare Plugin and Repository)
          • [Apply Plugin and Dependency](#Apply Plugin and Dependency)
          • [Configure Code Generation Dir and Tools](#Configure Code Generation Dir and Tools)
          • [Compile Proto File](#Compile Proto File)
          • [Auto Generate Class Files](#Auto Generate Class Files)
          • [Write and Read Data Directly Through PB File](#Write and Read Data Directly Through PB File)
          • [Create a Google RPC Server Transmitting with ProtoBuffer](#Create a Google RPC Server Transmitting with ProtoBuffer)
          • [Create a Google RPC Client](#Create a Google RPC Client)
Declare Plugin and Repository
kotlin 复制代码
pluginManagement {
    plugins {
        id("org.jetbrains.kotlin.jvm") version "2.0.0" apply false
        id("com.google.protobuf") version "0.9.2" apply false
    }
}

dependencyResolutionManagement {
    repositoriesMode = RepositoriesMode.PREFER_SETTINGS
    repositories {
        mavenLocal()
        google()
        mavenCentral()
        gradlePluginPortal()
    }
}
Apply Plugin and Dependency
kotlin 复制代码
plugins {
    id("org.jetbrains.kotlin.jvm")
    id("com.google.protobuf")
}


java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(8)
    }
}

dependencies {
    api("io.github.hellogoogle2000:kotlin-commons:+")
    api("com.google.protobuf:protobuf-kotlin:3.22.2")
    api("io.grpc:grpc-protobuf:1.54.0")
    api("io.grpc:grpc-netty-shaded:1.54.0")
    api("io.grpc:grpc-kotlin-stub:1.3.0")
    api("org.apache.tomcat:annotations-api:6.0.53")
}
Configure Code Generation Dir and Tools
kotlin 复制代码
protobuf {
    protoc {
        artifact = "com.google.protobuf:protoc:3.22.2"
    }
    plugins {
        create("rpc-java") {
            artifact = "io.grpc:protoc-gen-grpc-java:1.54.0"
        }
        create("rpc-kotlin") {
            artifact = "io.grpc:protoc-gen-grpc-kotlin:1.3.0:jdk8@jar"
        }
    }
    generateProtoTasks {
        all().forEach {
            it.plugins {
                create("rpc-java")
            }
            it.plugins {
                create("rpc-kotlin")
            }
            it.builtins {
                create("kotlin")
            }
        }
    }
}
Compile Proto File
groovy 复制代码
syntax = "proto3";

package com.kotlin.sample;

option java_multiple_files = true;
option java_package = "com.kotlin.sample.proto";
option java_outer_classname = "UserProto";

message UserListWrapper {
  repeated User list = 1;
}

message User {
  int32 id = 1;
  string name = 2;
  repeated Course courses = 3;
}

message Course {
  int32 id = 1;
  string name = 2;
}

message GetUserRequest {
  int32 pageSize = 1;
  int32 pageIndex = 2;
}

message GetUserResponse {
  repeated User users = 1;
}

service UserService {
  rpc GetUserList (GetUserRequest) returns (GetUserResponse) {}
}
Auto Generate Class Files

rebuild project, plugin will auto-generate all required files

Write and Read Data Directly Through PB File
kotlin 复制代码
import com.kotlin.sample.proto.User
import com.kotlin.sample.proto.UserListWrapper
import com.kotlin.sample.proto.user
import com.kotlin.sample.proto.userListWrapper
import x.kotlin.commons.string.UUID
import kotlin.io.path.Path
import kotlin.io.path.inputStream
import kotlin.io.path.outputStream

fun main() {
    // create user objects
    val users = mutableListOf<User>()
    repeat(2) {
        val user = user {
            id = UUID.hashCode()
            name = UUID.short()
        }
        users.add(user)
    }
    // create pb file
    val path = Path("/home/easing/temp/users.pb")
    // write to pb file
    val userListWrapper1 = userListWrapper { list.addAll(users) }
    path.outputStream().use { userListWrapper1.writeTo(it) }
    // read from pb file
    val userListWrapper2 = path.inputStream().use { UserListWrapper.parser().parseFrom(it) }
    println(userListWrapper1 == userListWrapper2)
}
Create a Google RPC Server Transmitting with ProtoBuffer
kotlin 复制代码
import com.kotlin.sample.proto.*
import io.grpc.ServerBuilder
import x.kotlin.commons.string.UUID

private class UserService : UserServiceGrpcKt.UserServiceCoroutineImplBase() {
    override suspend fun getUserList(request: GetUserRequest): GetUserResponse {
        val users = mutableListOf<User>()
        repeat(2) {
            val user = user {
                id = UUID.hashCode()
                name = UUID.short()
            }
            users.add(user)
        }
        return getUserResponse { this.users.addAll(users) }
    }
}

fun main() {
    val server = ServerBuilder
        .forPort(10001)
        .addService(UserService())
        .build()
    server.start()
    server.awaitTermination()
}
Create a Google RPC Client
kotlin 复制代码
import com.kotlin.sample.proto.UserServiceGrpcKt
import com.kotlin.sample.proto.getUserRequest
import io.grpc.ManagedChannelBuilder

suspend fun main() {
    val channel = ManagedChannelBuilder
        .forTarget("localhost:10001")
        .usePlaintext()
        .build()
    val service = UserServiceGrpcKt.UserServiceCoroutineStub(channel)
    val request = getUserRequest {
        pageSize = 10
        pageIndex = 0
    }
    val getUserResponse = service.getUserList(request)
    println(getUserResponse.usersList)
}
相关推荐
Digitally几秒前
如何从 Android 设备打印短信(5 种方法)
android
casual_clover8 分钟前
Android 中 打开文件选择器(ACTION_OPEN_DOCUMENT )
android
_龙小鱼_1 小时前
卡顿检测与 Choreographer 原理
android·kotlin
云手机管家2 小时前
账号风控突破:云手机设备指纹篡改检测与反制技术解析
android·运维·网络协议·网络安全·智能手机·矩阵·自动化
千里马-horse3 小时前
Detected for tasks ‘compileDebugJavaWithJavac‘ (17) and ‘kspDebugKotlin‘ (21).
android·jdk·kspdebugkotlin
柯南二号5 小时前
【Android】Android 实现一个依赖注入的注解
android
archko7 小时前
语音识别-3,添加ai问答
android·人工智能
奔跑吧 android12 小时前
【android bluetooth 案例分析 03】【PTS 测试 】【PBAP/PCE/SGSIT/SERR/BV-01-C】
android·pts·aosp·pbap·sgsit
難釋懷15 小时前
Android开发-Application
android
seven272916 小时前
Android 适配之——targetSdkVersion 30升级到31-34需要注意些什么?
android·版本设置31-34·targetsdk