Google gRPC 入门案例实战

x33g5p2x  于2022-06-06 转载在 其他  
字(3.9k)|赞(0)|评价(0)|浏览(302)

一 点睛

Protobuf 可以对消息进行编码和解码,但必须借助 Netty 等通信技术才能进行传输消息。Google 公司将 Protobuf 和 Netty 进行了结合,并在此基础上开发了一歀新的高性能的 RPC 框架——gRPC。

gRPC 是基于 HTTP/2 协议标准的,不过 HTTP/2 完全兼容 HTTP/1 的语义,因此在开发时,不用担心两种协议之间的差异。

二 gRPC 环境搭建步骤

1 访问 GitHub - grpc/grpc-java: The Java gRPC implementation. HTTP/2 based RPC

https://github.com/grpc/grpc-java下载 grpc,这里使用 v1.15.0

2 通过 Git 命令,对其进行下载
git clone -b v1.15.0 https://github.com/grpc/grpc-java

三 入门案例

以官方的 examples 中的 HelloWorld 示例进行说明。

1 protobuf 文件

syntax = "proto3";

option java_multiple_files = true;

option java_package = "io.grpc.examples.helloworld";

option java_outer_classname = "HelloWorldProto";

option objc_class_prefix = "HLW";

package helloworld;

// 接口定义

service Greeter {

// 接口方法

rpc SayHello (HelloRequest) returns (HelloReply) {}

}

// 请求消息

message HelloRequest {

string name = 1;

}

// 响应消息

message HelloReply {

string message = 1;

}

2 服务端代码

  1. package io.grpc.examples.helloworld;
  2. import io.grpc.Server;
  3. import io.grpc.ServerBuilder;
  4. import io.grpc.stub.StreamObserver;
  5. import java.io.IOException;
  6. import java.util.logging.Logger;
  7. /**
  8. * Hello world 的服务端
  9. */
  10. public class HelloWorldServer {
  11. private static final Logger logger = Logger.getLogger(HelloWorldServer.class.getName());
  12. private Server server;
  13. // 启动服务端
  14. private void start() throws IOException {
  15. /* 监听端口 */
  16. int port = 50051;
  17. server = ServerBuilder.forPort(port)
  18. .addService(new GreeterImpl()) // 服务端对应的实现类
  19. .build()
  20. .start();
  21. logger.info("Server started, listening on " + port);
  22. Runtime.getRuntime().addShutdownHook(new Thread() {
  23. @Override
  24. public void run() {
  25. // 虚拟机退出时,将这些下面这段代码
  26. System.err.println("*** shutting down gRPC server since JVM is shutting down");
  27. HelloWorldServer.this.stop();
  28. System.err.println("*** server shut down");
  29. }
  30. });
  31. }
  32. // 关闭服务器
  33. private void stop() {
  34. if (server != null) {
  35. server.shutdown();
  36. }
  37. }
  38. private void blockUntilShutdown() throws InterruptedException {
  39. if (server != null) {
  40. server.awaitTermination();
  41. }
  42. }
  43. // 启动服务端
  44. public static void main(String[] args) throws IOException, InterruptedException {
  45. final HelloWorldServer server = new HelloWorldServer();
  46. server.start();
  47. server.blockUntilShutdown();
  48. }
  49. // 服务实现类
  50. static class GreeterImpl extends GreeterGrpc.GreeterImplBase {
  51. @Override
  52. public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
  53. HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + req.getName()).build();
  54. responseObserver.onNext(reply);
  55. responseObserver.onCompleted();
  56. }
  57. }
  58. }

3 客户端代码

  1. package io.grpc.examples.helloworld;
  2. import io.grpc.ManagedChannel;
  3. import io.grpc.ManagedChannelBuilder;
  4. import io.grpc.StatusRuntimeException;
  5. import java.util.concurrent.TimeUnit;
  6. import java.util.logging.Level;
  7. import java.util.logging.Logger;
  8. /**
  9. * Hello world 的客户端
  10. */
  11. public class HelloWorldClient {
  12. private static final Logger logger = Logger.getLogger(HelloWorldClient.class.getName());
  13. private final ManagedChannel channel;
  14. private final GreeterGrpc.GreeterBlockingStub blockingStub;
  15. /** 连接服务端的构造器 */
  16. public HelloWorldClient(String host, int port) {
  17. this(ManagedChannelBuilder.forAddress(host, port)
  18. .usePlaintext()
  19. .build());
  20. }
  21. /** 初始化通道 */
  22. HelloWorldClient(ManagedChannel channel) {
  23. this.channel = channel;
  24. blockingStub = GreeterGrpc.newBlockingStub(channel);
  25. }
  26. // 关闭通道
  27. public void shutdown() throws InterruptedException {
  28. channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
  29. }
  30. /** 客户端请求 */
  31. public void greet(String name) {
  32. logger.info("Will try to greet " + name + " ...");
  33. HelloRequest request = HelloRequest.newBuilder().setName(name).build();
  34. HelloReply response;
  35. try {
  36. response = blockingStub.sayHello(request);
  37. } catch (StatusRuntimeException e) {
  38. logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
  39. return;
  40. }
  41. logger.info("Greeting: " + response.getMessage());
  42. }
  43. public static void main(String[] args) throws Exception {
  44. HelloWorldClient client = new HelloWorldClient("localhost", 50051);
  45. try {
  46. String user = "world";
  47. if (args.length > 0) {
  48. user = args[0];
  49. }
  50. client.greet(user);
  51. } finally {
  52. client.shutdown();
  53. }
  54. }
  55. }

四 测试

1 启动服务端

2 启动客户端

3 服务端打印

信息: Server started, listening on 50051

4 客户端打印

六月 04, 2022 7:49:19 上午 io.grpc.examples.helloworld.HelloWorldClient greet

信息: Will try to greet world ...

六月 04, 2022 7:49:20 上午 io.grpc.examples.helloworld.HelloWorldClient greet

信息: Greeting: Hello world

相关文章