Grpc应用(一),基本实现

使用grpc可以用来进行不同系统之间的信息交互,而且grpc不限于java,使用同一个proto文件可以在不同的编程语言之间交互。

上面这张图介绍了proto文件的语法,对应proto3.0,具体更多的内容请参考文档:

下面我们先讲一下如何在java中通过proto文件生成java代码,然后再讲如何使用。

添加如下依赖与插件:

Java代码

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

这样一来,在进行mvn compile时,会自动去src/main/resources/proto目录下查找proto文件,并在target目录里生成对应的.java、.class文件。

下面我们写一个服务端、一个客户端的helloworld程序,proto文件如下:

Java代码

  1. syntax = "proto3";
  2. package grpc;
  3. option java_package = "com.zk_chs.grpc";
  4. option java_outer_classname = "HelloWorldServiceProto";
  5. option java_multiple_files = true;
  6. service HelloWorldService {
  7. rpc SayHello (HelloWorldRequest) returns (HelloWorldResponse) {}
  8. }
  9. message HelloWorldRequest {
  10. string request = 1;
  11. }
  12. message HelloWorldResponse {
  13. string response = 1;
  14. }

当有option java_package存在时,会覆盖package属性,生成的文件如下:

接下来,需要先实现我们定义的HelloWorldService服务接口,该接口只需在服务端实现,客户端不用实现:

Java代码

  1. public class HelloWorldRpcServiceImpl implements HelloWorldRpcServiceGrpc.HelloWorldRpcService {
  2. @Override
  3. public void sayHello(HelloWorldRequest request, StreamObserver<HelloWorldResponse> responseObserver) {
  4. String req = request.getRequest;
  5. HelloWorldResponse resp = HelloWorldResponse.newBuilder
  6. .setResponse("hello " + req)
  7. .build;
  8. responseObserver.onNext(resp);
  9. responseObserver.onCompleted;
  10. }
  11. }

服务端实现:

Java代码

  1. public class GrpcServer {
  2. private final int port = 38628;
  3. private Server server;
  4. private void start throws IOException {
  5. server = ServerBuilder.forPort(port)
  6. .addService(HelloWorldRpcServiceGrpc.bindService(new HelloWorldRpcServiceImpl)) // 能继续使用.addService添加多个服务
  7. .build
  8. .start;
  9. Runtime.getRuntime.addShutdownHook(new Thread {
  10. @Override
  11. public void run {
  12. GrpcServer.this.stop;
  13. }
  14. });
  15. }
  16. private void stop {
  17. if (server != null) {
  18. server.shutdown;
  19. }
  20. }
  21. private void blockUntilShutdown throws InterruptedException {
  22. if (server != null) {
  23. server.awaitTermination;
  24. }
  25. }
  26. public static void main(String[] args) throws IOException, InterruptedException {
  27. final GrpcServer server = new GrpcServer;
  28. server.start;
  29. server.blockUntilShutdown;
  30. }
  31. }

客户端实现:

Java代码

  1. public class GrpcClient {
  2. private final ManagedChannel channel;
  3. private final HelloWorldRpcServiceGrpc.HelloWorldRpcServiceBlockingStub blockingStub;
  4. public GrpcClient(String host, int port) {
  5. channel = ManagedChannelBuilder.forAddress(host, port)
  6. .usePlaintext(true)
  7. .build;
  8. blockingStub = HelloWorldRpcServiceGrpc.newBlockingStub(channel);
  9. }
  10. public void shutdown throws InterruptedException {
  11. channel.shutdown.awaitTermination(5, TimeUnit.SECONDS);
  12. }
  13. public String request(String req) {
  14. HelloWorldRequest request = HelloWorldRequest.newBuilder
  15. .setRequest(req)
  16. .build;
  17. return blockingStub.sayHello(request).getResponse;
  18. }
  19. public static void main(String[] args) throws Exception {
  20. GrpcClient client = new GrpcClient("localhost", 38628);
  21. String req = "world!";
  22. String response = client.request(req);
  23. System.out.println(response);
  24. }
  25. }

然后进行测试,首先启动GrpcServer,再运行GrpcClient,在client的控制台能看到如下信息:

一个简易的grpc服务就完成了,当然,还有很多的不足:

1、例如异常信息处理(grpc有内置的异常信息)

2、连接每次都会断开,没有重复利用,效率低

下次的博客大概会介绍一下解决方法,比如采用commons-pool2连接池

Grpc应用(二)、搭配commons-pool2连接池,
http://zk-chs.iteye.com/blog/2308730

原文链接:,转发请注明来源!