grpc-java (Google gRPC) 安装使用


(PS : 第一次发布博客 不喜欢不要乱喷)
可看本人 : 云笔记分享链接 

据说 GRPC 是那个啥基于 Protobuf3 做的, 百度一下没有相关的文档,那就只有自己扣官网文档了
编辑时间 : 2016-01-24 18:13:39

首先是准备环境
我是用的linux 环境
碍于Protobuf 官网需要墙外,所以有条件的墙外看看官网有木有,编译好的包(此刻没有啊,只找到win32版本的)
苦逼的编译了大半天啊

说正事 :
首先我们要 编译安装 protobuf3

Window下编译这边 -- https://github.com/google/protobuf/tree/master/cmake
对windows不熟悉 - 真是对不住了啊

准本工作 : 安装 git
$ sudo apt-get -y install git
$ sudo apt-get install autoconf automake libtool curl
官网都有例子,把命令整理一下而已 如下 :



$ git clone https://github.com/google/protobuf.git
需要自己切换到 想编译的版本 -- 呵呵
$ ./autogen.sh


$ ./configure
$ make
$ make check
$ sudo make install

$ sudo ldconfig 
# refresh(刷新) shared(共享) library cache(缓存).
编译安装 -- 完毕

使用Java 那么现在来 弄 grpc 的 grpc-java 插件(其他插件是异曲同工)
如果自我觉得英文水平不错,或者想自己去看一手文档 -->> 请移步到(Github 文档) 地址 https://github.com/grpc/grpc-java/tree/master/compiler
首先从 github 上clone 下来 grpc-java 这个项目

$ git clone https://github.com/grpc/grpc-java.git


说是移步到 compiler 这个文件夹

$ cd $GRPC_JAVA_ROOT/compiler

执行编译命令  ( 注意 这个玩意编译的时候最好是 **墙外吧 - 要不然呵呵 我已经试过了)

$ ../gradlew java_pluginExecutable
待编译完成,运行这个玩意 (可以跳过试试 )

$ ../gradlew test




在 则这个文件夹(build/binaries/java_pluginExecutable/) 找到 protoc-gen-grpc-java 文件 主要是这个文件起作用哟
不不想编译的 到网盘下载去 链接: http://pan.baidu.com/s/1qX66mSG 密码: ik3h

OK 下面来重点了  使用插件 生成 service


$ protoc --plugin=protoc-gen-grpc-java=/home/cxx/soft/protoc-gen-grpc-java --grpc-java_out=./src --proto_path=./ *.proto


说明一下参数
--plugin : 插件名称 后面等号是指定 插件程序的位置
--grpc-java_out : 这个不用多说了 生成代码输出位置 
    其他用法(nano) :   --grpc-java_out=nano=true:"$OUTPUT_FILE"
--proto_path : 源文件目录  , 空格 后啊面需要 跟随 .proto 文件名称
生成结束 ---

代码呵呵
[.proto 文件]

syntax = "proto3";
option java_package = "com.fomky.mbug.server.protobuf.vo";

option java_outer_classname = "Coder";

/**
 * Coder Our ---- main user info haha
 */
message CoderVo {
     string cid = 1;
     string email = 2;
     string phone = 3;
     string pass = 4;
     string name = 5;
     sint32 sex = 6;
     string img = 7;
     sint64 birth = 8;
     sint32 age = 9;
     string remark = 10;
     string profession = 11;
     string company = 12;
     string poskey = 13;
     string city = 14;
     sint32 lvl = 15;
     sint64 exp = 16;
     sint32 bug = 17;
     sint32 fbug = 18;
     sint32 dbug = 19;
     sint32 rbug = 20;
     string rname = 21;
     string card = 22;
    //Sex enum
    enum SEX {
        M = 0;
        F = 1;
    }
}
syntax = "proto3";
option java_package = "com.fomky.mbug.server.protobuf";

option java_outer_classname = "CoderBase";
import "Coder.proto";
service CoderService {
    rpc SayHello(CoderRequest) returns (CoderResponse);
}

enum CMD {
    REG = 0; //register new coder
    SIGNIN = 1; // sign in system
    UPINFO = 2; // update coder info
    SIGNOUT = 3; // sign out our system
}

message CoderRequest {
     CMD cmd = 1;
    //Coder information
     CoderVo coder = 2;
     string msg =3;
}

message CoderResponse {
     CMD cmd = 1;
    //error code
     Status sta = 2;
    //Coder information
     CoderVo coder = 3;
    //the message show
     string msg = 4;
    enum Status {
        OK = 0;
        ERR = 1;
        OTH = 2;
    }
}



[接口实现代码]

import com.fomky.mbug.server.protobuf.CoderBase;
import com.fomky.mbug.server.protobuf.CoderServiceGrpc;
import io.grpc.stub.StreamObserver;
import org.apache.log4j.Logger;

/**
* Deal coder data. like register sign update....
* This need Signal Object;
*
* @author Created by Fomky on 2016/1/22.
*/
public class CoderServiceImpl implements CoderServiceGrpc.CoderService {
    Logger logger = Logger.getLogger(CoderServiceImpl.class);

    @Override
    public void sayHello(CoderBase.CoderRequest request, StreamObserver<CoderBase.CoderResponse> responseObserver) {
        logger.info("Request : " + request);
        CoderBase.CoderResponse.Builder builder = CoderBase.CoderResponse.newBuilder();
        builder.setCmd(request.getCmd());
        builder.setMsg(request.getMsg());
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
        switch (request.getCmd()) {
            case REG: { //Register
                break;
            }
            case SIGNIN: { // Sign in
                break;
            }
            case SIGNOUT: { // sign out
                break;
            }
            case UPINFO: { // update user info
                break;
            }
        }
    }
}

 

[启动服务代码]

import com.fomky.mbug.server.coder.service.CoderServiceImpl;
import com.fomky.mbug.server.protobuf.CoderServiceGrpc;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import org.apache.log4j.Logger;

/**
* The main class of server
*
* @author Fomky
* @date 2016-01-22 14:07:42
*/
public class MbugServer {
    private static int port = 8080;
    private static Server server;
    private static Logger logger = Logger.getLogger(CoderServiceImpl.class);

    public static void main(String[] args) throws Exception {
        server = ServerBuilder.forPort(port)
                //can add multi service
                .addService(CoderServiceGrpc.bindService(new CoderServiceImpl()))
                .build();
        logger.info("Server started, listening on " + port);
        server.start();
        logger.info("Server started, listening on " + port);
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                // Use stderr here since the logger may has been reset by its JVM shutdown hook.
                System.err.println("*** shutting down gRPC server since JVM is shutting down");
                MbugServer.stop();
                System.err.println("*** server shut down");
            }
        });
        Thread.sleep(Integer.MAX_VALUE);
    }

    private static void stop() {
        server.shutdownNow();
    }
}

 

[客户端代码]

@Test
public void testHello(){
    ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost",8080)
            .usePlaintext(true)
            .build();
    CoderServiceGrpc.CoderServiceBlockingStub stub = CoderServiceGrpc.newBlockingStub(channel);
    CoderBase.CoderRequest.Builder builder = CoderBase.CoderRequest.newBuilder();
    builder.setMsg("Just test request");
    stub.sayHello(builder.build());
    builder.setCmd(CoderBase.CMD.REG);
    long start = System.currentTimeMillis();
    for (int i = 0; i < 10; i++) {
        CoderBase.CoderResponse response = stub.sayHello(builder.build());
    }
    System.out.println("Wist time : " + (System.currentTimeMillis() - start)/1000 + " sec");
}

 


移步到 github 官方正宗 --->; https://github.com/grpc/grpc-java/tree/master/examples

被文章源码 : https://github.com/Fomky/mbug




猜你喜欢

转载自fomky.iteye.com/blog/2273944