Create a new Gradle project for the archetype:
Bash
mkdir kotlin-grpc-archetype
cd kotlin-grpc-archetype
gradle init --type java-gradle-plugin --dsl kotlin
Create a directory to represent the structure of the generated projects:
Bash
mkdir template
Inside the template directory, create the following files and directories:
MarkDown
template
├── build.gradle.kts
├── src
│ ├── main
│ │ ├── kotlin
│ │ │ └── com
│ │ │ └── example
│ │ └── proto
│ └── ...
└── ...
Kotlin
plugins {
application
id("com.google.protobuf") version "0.8.15"
kotlin("jvm") version "1.8.10"
}
group = "com.example"
version = "0.0.1"
repositories {
mavenCentral()
}
dependencies {
implementation("io.grpc:grpc-kotlin-stub:1.2.1")
implementation("io.grpc:grpc-protobuf:1.2.1")
implementation("com.google.protobuf:protobuf-kotlin:3.11.1")
}
protobuf {
protoc {
artifact = "com.google.protobuf:protoc:3.11.1"
}
plugins {
grpc {
artifact = "io.grpc:protoc-gen-grpc-kotlin:1.2.1"
}
}
generateProtoTasks {
all()*.plugins {
grpc {}
}
}
}
application {
mainClass.set("com.example.GreeterServerKt")
}
Protobuf
syntax = "proto3";
package helloworld;
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
Kotlin
package com.example
import io.grpc.Server
import io.grpc.ServerBuilder
import helloworld.GreeterGrpcKt
import helloworld.HelloReply
import helloworld.HelloRequest
class GreeterServer : GreeterGrpcKt.Greeter {
override suspend fun sayHello(request: HelloRequest): HelloReply {
val reply = HelloReply.newBuilder().setMessage("Hello, ${request.name}!").build()
return reply
}
}
fun main() {
val server = ServerBuilder.forPort(50051)
.addService(GreeterServer())
.build()
.start()
println("Server started on port 50051")
server.awaitTermination()
}
Kotlin
package com.example
import io.grpc.ManagedChannel
import io.grpc.ManagedChannelBuilder
import helloworld.GreeterGrpcKt
import helloworld.HelloRequest
suspend fun main() {
val channel = ManagedChannelBuilder.forAddress("localhost", 50051)
.usePlaintext()
.build()
val stub = GreeterGrpcKt.Greeter(channel)
val request = HelloRequest.newBuilder().setName("John").build()
val response = stub.sayHello(request)
println("Response: ${response.message}")
channel.shutdown()
}
In the root build.gradle.kts of your archetype project:
Kotlin
plugins {
id("java-gradle-plugin")
}
group = "com.example"
version = "0.0.1"
gradlePlugin {
plugins {
create("kotlinGrpcArchetype") {
id = "com.example.kotlin-grpc-archetype"
implementationClass = "com.example.KotlinGrpcArchetype"
}
}
}
From the root of your archetype project, run:
Bash
./gradlew install
Use the gradle init command to generate a new project based on your archetype:
Bash
gradle init --type kotlin-grpc-archetype --dsl kotlin
Follow the prompts to provide the required information (group ID, artifact ID, etc.).
That's it! You now have a Kotlin gRPC "Hello World" archetype that can be used to generate new projects.