禅与计算机程序设计艺术Kotlin专题Kotlin

Kotlin IDEA下用Gradle GRPC 简单教程

2017-12-23  本文已影响160人  想入飞飞___

0.Gradle配置GRPC

我用的是idea,首先我用Gradle来构建项目,项目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文件夹,用来放proto的,以下为测试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控制台下输入“Gradlew build”来生成源码

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编译

进入项目根目录,命令行输出下面的

gradlew build

5运行

先运行Server再运行client,成功接收到client传来的消息,如图


成功.png
上一篇下一篇

猜你喜欢

热点阅读