[ 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)
}
相关推荐
斗锋在干嘛2 小时前
Android里面内存优化
android
jiet_h4 小时前
深入解析Kapt —— Kotlin Annotation Processing Tool 技术博客
android·开发语言·kotlin
alexhilton4 小时前
实战:探索Jetpack Compose中的SearchBar
android·kotlin·android jetpack
uhakadotcom5 小时前
EventBus:简化组件间通信的利器
android·java·github
笑鸿的学习笔记6 小时前
ROS2笔记之服务通信和基于参数的服务通信区别
android·笔记·microsoft
8931519607 小时前
Android开发融云获取多个会话的总未读数
android·android开发·android教程·融云获取多个会话的总未读数·融云未读数
高林雨露7 小时前
Java对比学习Kotlin的详细指南(一)
java·学习·kotlin
zjw_swun7 小时前
实现了一个uiautomator玩玩
android
pengyu7 小时前
系统化掌握Dart网络编程之Dio(二):责任链模式篇
android·flutter·dart
水w7 小时前
【Android Studio】如何卸载干净(详细步骤)
android·开发语言·android studio·activity