Kotlin IDEA下用Gradle GRPC 簡(jiǎn)單教程

0.Gradle配置GRPC

我用的是idea,首先我用Gradle來(lái)構(gòu)建項(xiàng)目,項(xiàng)目grpc如下

group 'dd'
version '1.0-SNAPSHOT'

buildscript {
    ext.kotlin_version = '1.1.4'

    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.1'
    }
}

apply plugin: 'kotlin'
apply plugin: 'com.google.protobuf'


protobuf {
    protoc {
        artifact = "com.google.protobuf:protoc:3.2.0"
    }
    plugins {
        grpc {
            artifact = 'io.grpc:protoc-gen-grpc-java:1.4.0'
        }
    }

    generatedFilesBaseDir = "src"

    generateProtoTasks {
        all()*.plugins {
            grpc {
                outputSubDir = "java"
            }
        }
    }
}

repositories {
    mavenCentral()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"

    compile 'io.grpc:grpc-netty:1.8.0'
    compile 'io.grpc:grpc-protobuf:1.8.0'
    compile 'io.grpc:grpc-stub:1.8.0'
}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

1.proto文件

在src\main目錄下,建立proto文件夾,用來(lái)放proto的,以下為測(cè)試proto

syntax="proto3";
package com.wyf;

service TestService{
    rpc test(Req) returns(Resp){}
}
enum Tt{
    T1 =0;
    T2 = 1;
}

message Req{
    string req=1;
}
message Resp{
    string resp =1;
}

在IDEA控制臺(tái)下輸入“Gradlew build”來(lái)生成源碼

2.Server端

Server端文件

import com.google.protobuf.Service
import com.wyf.La
javascript:void(null)
import com.wyf.TestServiceGrpc
import io.grpc.ServerBuilder
import io.grpc.stub.StreamObserver

fun main(args :Array<String>){

     var server = ServerBuilder
             .forPort(8899)
             .addService(TestService())
             .build()
             .start()
    server.awaitTermination()
    println("ss")
}

 class  TestService : TestServiceGrpc.TestServiceImplBase() {
    override fun test(request: La.Req?, responseObserver: StreamObserver<La.Resp>?) {
        println(request?.req)
    }
}

3.Client端

Client端文件

import com.wyf.La
import com.wyf.TestServiceGrpc
import io.grpc.ManagedChannelBuilder

fun main(args:Array<String>){

    var   channel = ManagedChannelBuilder.forAddress("127.0.0.1",8899)
            .usePlaintext(true)
            .build()

    var testStub = TestServiceGrpc.newBlockingStub(channel)
    var r = La.Req.newBuilder().setReq("112233445566").build()
    testStub.test(r)

}

4編譯

進(jìn)入項(xiàng)目根目錄,命令行輸出下面的

gradlew build

5運(yùn)行

先運(yùn)行Server再運(yùn)行client,成功接收到client傳來(lái)的消息,如圖


成功.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容