grpc-java快速体验

2021-07-01 10:17:00 浏览数 (1)

公司内部有的服务提供的是grpc协议的接口,所以使用demo快速了解一下

快速体验

  • 下载源码
代码语言:javascript复制
$ git clone -b v1.38.0 https://github.com/grpc/grpc-java
  • 编译
代码语言:javascript复制
$ cd grpc-java/examples
$ ./gradlew installDist
  • 运行服务器端
代码语言:javascript复制
$ ./build/install/examples/bin/hello-world-server
INFO: Server started, listening on 50051
  • 运行客户端
代码语言:javascript复制
$ ./build/install/examples/bin/hello-world-client
INFO: Will try to greet world ...
INFO: Greeting: Hello world

增加接口

  • 修改.proto文件(src/main/proto/helloworld.proto)
代码语言:javascript复制
// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
  // 下面这一行是新增的方法
  rpc SayHelloAgain (HelloRequest) returns (HelloReply) {}
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings
message HelloReply {
  string message = 1;
}
  • 修改服务端
代码语言:javascript复制
private class GreeterImpl extends GreeterGrpc.GreeterImplBase {

  @Override
  public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
    HelloReply reply = HelloReply.newBuilder().setMessage("Hello "   req.getName()).build();
    responseObserver.onNext(reply);
    responseObserver.onCompleted();
  }

  //增加这个方法
  @Override
  public void sayHelloAgain(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
    HelloReply reply = HelloReply.newBuilder().setMessage("Hello again "   req.getName()).build();
    responseObserver.onNext(reply);
    responseObserver.onCompleted();
  }
}
  • 修改客户端
代码语言:javascript复制
public void greet(String name) {
  logger.info("Will try to greet "   name   " ...");
  HelloRequest request = HelloRequest.newBuilder().setName(name).build();
  HelloReply response;
  try {
    response = blockingStub.sayHello(request);
  } catch (StatusRuntimeException e) {
    logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
    return;
  }
  logger.info("Greeting: "   response.getMessage());
  try {
    response = blockingStub.sayHelloAgain(request);
  } catch (StatusRuntimeException e) {
    logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
    return;
  }
  logger.info("Greeting: "   response.getMessage());
}

ps: 后面还可以再会增加从0开始完成一个grpc调用

参考

  • grpc-Quick start
rpc

0 人点赞