gRPC快速入门

水深无声 2022-07-21 01:09 308阅读 0赞

gRPC 是一个高性能、开源和通用的 RPC 框架,面向移动和 HTTP/2 设计。目前提供 C、Java 和 Go 语言版本,分别是:grpc, grpc-java, grpc-go. 其中 C 版本支持 C, C++, Node.js, Python, Ruby, Objective-C, PHP 和 C# 支持.

gRPC 基于 HTTP/2 标准设计,带来诸如双向流、流控、头部压缩、单 TCP 连接上的多复用请求等特。这些特性使得其在移动设备上表现更好,更省电和节省空间占用。

研究gRPC之前,需要先熟悉Protocol Buffers

Protocol Buffers (ProtocolBuffer/ protobuf )是Google公司开发的一种数据描述语言,类似于XML能够将结构化数据序列化,可用于数据存储、通信协议等方面。现阶段支持C++、JAVA、Python等三种编程语言。

一:编写IDL文件 send_mail.proto

  1. syntax = "proto3";
  2. option java_multiple_files = true;
  3. option java_package = "com.rpc.mail";
  4. option java_outer_classname = "SendMailServiceProto";
  5. message SendMailRequest {
  6. string recipient = 1;
  7. string title = 2;
  8. string content = 3;
  9. }
  10. message SendMailResponse {
  11. int32 code = 1;
  12. string msg = 2;
  13. }
  14. service SendMailService {
  15. rpc sendMail (SendMailRequest) returns (SendMailResponse) {}
  16. }

这里定义了一个请求参数SendMailRequest,一个返回参数SendMailResponse,一个接口SendMailService

新建一个maven项目,把上面的proto文件放到src/main/proto目录

pom.xml里面增加如下配置

  1. <dependencies>
  2. <dependency>
  3. <groupId>io.grpc</groupId>
  4. <artifactId>grpc-all</artifactId>
  5. <version>0.14.1</version>
  6. </dependency>
  7. </dependencies>
  8. <build>
  9. <extensions>
  10. <extension>
  11. <groupId>kr.motd.maven</groupId>
  12. <artifactId>os-maven-plugin</artifactId>
  13. <version>1.4.1.Final</version>
  14. </extension>
  15. </extensions>
  16. <plugins>
  17. <plugin>
  18. <groupId>org.xolstice.maven.plugins</groupId>
  19. <artifactId>protobuf-maven-plugin</artifactId>
  20. <version>0.5.0</version>
  21. <configuration>
  22. <protocArtifact>com.google.protobuf:protoc:3.0.0-beta-2:exe:${os.detected.classifier}
  23. </protocArtifact>
  24. <pluginId>grpc-java</pluginId>
  25. <pluginArtifact>io.grpc:protoc-gen-grpc-java:0.14.1:exe:${os.detected.classifier}
  26. </pluginArtifact>
  27. </configuration>
  28. <executions>
  29. <execution>
  30. <goals>
  31. <goal>compile</goal>
  32. <goal>compile-custom</goal>
  33. </goals>
  34. </execution>
  35. </executions>
  36. </plugin>
  37. </plugins>
  38. </build>

之后执行maven clean package即可生成java代码,生成的java代码在target\generated-sources\protobuf 目录

注意:插件里面的protobuf(protocArtifact、pluginArtifact)需要和grpc-core里面依赖的protobuf版本需要保持一致

二:编码

新建一个maven项目(也可以直接使用上一步创建的项目),在pom.xml里面加入如下配置

  1. <dependencies>
  2. <dependency>
  3. <groupId>io.grpc</groupId>
  4. <artifactId>grpc-all</artifactId>
  5. <version>0.14.1</version>
  6. </dependency>
  7. </dependencies>

然后把target\generated-sources\protobuf\java 和 target\generated-sources\protobuf\grpc-java 里面的代码放到src目录中去
目录结构如下:

Center

接下来,写接口的实现类

  1. package com.rpc.mail;
  2. import io.grpc.stub.StreamObserver;
  3. public class SendMailServiceImpl implements SendMailServiceGrpc.SendMailService {
  4. public void sendMail(SendMailRequest request, StreamObserver<SendMailResponse> responseObserver) {
  5. System.out.println(request.getRecipient() + "\t" + request.getTitle() + "\t" + request.getContent());
  6. //这里是具体的业务逻辑
  7. SendMailResponse resp = SendMailResponse.newBuilder().setCode(0).setMsg("OK").build();
  8. //设置返回结果
  9. responseObserver.onNext(resp);
  10. responseObserver.onCompleted();
  11. }
  12. }

服务端:

  1. package com.rpc.mail;
  2. import io.grpc.Server;
  3. import io.grpc.netty.NettyServerBuilder;
  4. public class GrpcServer {
  5. public static void main(String[] args) throws Exception {
  6. Server server = NettyServerBuilder.forPort(8080).addService(SendMailServiceGrpc.bindService(new SendMailServiceImpl())).build();
  7. server.start();
  8. System.out.println("server startup at 8080");
  9. server.awaitTermination();
  10. }
  11. }

客户端:

  1. package com.rpc.mail;
  2. import java.util.concurrent.TimeUnit;
  3. import com.rpc.mail.SendMailServiceGrpc.SendMailServiceBlockingStub;
  4. import io.grpc.ManagedChannel;
  5. import io.grpc.netty.NettyChannelBuilder;
  6. public class GrpcClient {
  7. public static void main(String[] args) throws Exception {
  8. ManagedChannel channel = NettyChannelBuilder.forAddress("127.0.0.1", 8080).usePlaintext(true).build();
  9. //同步调用(异步调用的话,就是:SendMailServiceGrpc.newFutureStub(channel))
  10. SendMailServiceBlockingStub stub = SendMailServiceGrpc.newBlockingStub(channel);
  11. //设置请求参数
  12. SendMailRequest param = SendMailRequest.newBuilder().setRecipient("admin@google.com").setTitle("运维邮件").setContent("SOA服务挂了").build();
  13. SendMailResponse resp = stub.sendMail(param);
  14. System.out.println(resp.getMsg() + "\t" + resp.getCode());
  15. //close
  16. channel.shutdown().awaitTermination(1, TimeUnit.SECONDS);
  17. }
  18. }

先启动服务端,之后,客户端就可以进行调用了。这样,一个简单的Grpc例子就做好了。

发表评论

表情:
评论列表 (有 0 条评论,308人围观)

还没有评论,来说两句吧...

相关阅读

    相关 gRPC快速整合SpringCloud

    gRPC是由 google开发的一个高性能、通用的开源RPC框架,主要面向移动应用开发且基于HTTP/2协议标准而设计,同时支持大多数流行的编程语言。它是一种与语言、平台无关、

    相关 gRPC快速入门

    gRPC 是一个高性能、开源和通用的 RPC 框架,面向移动和 HTTP/2 设计。目前提供 C、Java 和 Go 语言版本,分别是:grpc, grpc-java, grp

    相关 GRPC基础入门

      项目中要使用rpc协议框架来实现两个系统之间的接口调用。A系统调用B系统的相应接口,因为考虑到http请求会包含更多冗余信息,造成请求过大,因此选用了rpc众多框架中的gr