gRPC整合Gradle

首先阅读官方文档:

https://github.com/grpc/grpc-java

一、添加依赖

Github上如是说:

添加protobuf-gradle-plugin插件完整如下

group 'com.dongqiang'
version '1.0'

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

sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile(
            "io.netty:netty-all:4.1.10.Final",
            "com.google.protobuf:protobuf-java:3.3.1",
            "com.google.protobuf:protobuf-java-util:3.3.1",
            'org.apache.thrift:libthrift:0.10.0',
            'io.grpc:grpc-netty:1.4.0',
            'io.grpc:grpc-protobuf:1.4.0',
            'io.grpc:grpc-stub:1.4.0'

    )
}

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        // ASSUMES GRADLE 2.12 OR HIGHER. Use plugin version 0.7.5 with earlier
        // gradle versions
        classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.0'
    }
}

protobuf {
    protoc {
        artifact = "com.google.protobuf:protoc:3.2.0"
    }

    plugins {
        grpc {
            artifact = 'io.grpc:protoc-gen-grpc-java:1.4.0'
        }
    }

    generateProtoTasks {
        all()*.plugins {
            grpc {}
        }
    }
}

二、定义Proto文件

根据文档,我们在src/main/下创建目录proto:Student.proto

syntax = "proto3";

package com.dongqiang.proto;

option java_package = 'com.dongqiang.proto';
option java_outer_classname = 'StudentProto';
option java_multiple_files = true;

service StudentService {
    rpc GetRealNameByUserName(MyRequest) returns (MyResponse) {}
}

message MyRequest {
    string username = 1;
}

message MyResponse {
    string realname = 2;
}

然后,在命令行执行命令:

使用gradle generateProto命令会根据Student.proto文件将message和service转换为Java.

如下图所示:

接着,把生成的Java文件拖到com.dongqiang.proto包下:

下面基于上面的结果编写客户端与服务端:

GrpcServer.java

package com.dongqiang.grpc;


import io.grpc.Server;
import io.grpc.ServerBuilder;

import java.io.IOException;

/**
 * Created by dongqiang on 2017/7/11.
 */
public class GrpcServer {

    private Server server;

    private void start() throws IOException {
        server = ServerBuilder.forPort(8899).addService(new StudentServiceImpl()).build().start();
        System.out.println("server start.");

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("jvm 关闭");
            GrpcServer.this.stop();
        }));

    }

    private void waitTermination() throws InterruptedException {
        if (null != server) {
            server.awaitTermination();
        }
    }

    private void stop() {
        if (null != server) {
            server.shutdown();
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        GrpcServer grpcServer = new GrpcServer();
        grpcServer.start();
        grpcServer.waitTermination();
    }
}

StudentServiceImpl.java

package com.dongqiang.grpc;

import com.dongqiang.proto.MyRequest;
import com.dongqiang.proto.MyResponse;
import com.dongqiang.proto.StudentServiceGrpc;
import io.grpc.stub.StreamObserver;

/**
 * Created by dongqiang on 2017/7/11.
 */
public class StudentServiceImpl extends StudentServiceGrpc.StudentServiceImplBase {

    @Override
    public void getRealNameByUserName(MyRequest request, StreamObserver<MyResponse> responseObserver) {
        System.out.println(request.getUsername());

        responseObserver.onNext(MyResponse.newBuilder().setRealname("张三").build());
        responseObserver.onCompleted();
    }
}

GrpcClient.java

package com.dongqiang.grpc;

import com.dongqiang.proto.MyRequest;
import com.dongqiang.proto.MyResponse;
import com.dongqiang.proto.StudentServiceGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

import java.util.concurrent.TimeUnit;

/**
 * Created by dongqiang on 2017/7/11.
 */
public class GrpcClient {
    public static void main(String[] args) throws InterruptedException {
        ManagedChannel channel = ManagedChannelBuilder
                .forAddress("localhost", 8899).usePlaintext(true).build();
        StudentServiceGrpc.StudentServiceBlockingStub blockingStub = StudentServiceGrpc.newBlockingStub(channel);
        MyResponse response = blockingStub.getRealNameByUserName(MyRequest.newBuilder().setUsername("zhangsan")
        .build());
        System.out.println(response.getRealname());
        channel.awaitTermination(3000, TimeUnit.SECONDS);
    }
}

先运行Server,再运行Client.

客户端:

results matching ""

    No results matching ""