什么是Grpc

gRPC 是一个现代开源的高性能 RPC 框架,可以在任何环境下运行。它可以有效地将数据中心内和跨数据中心的服务与可插拔支持进行负载均衡、跟踪、健康检查和认证。它也适用于分布式计算,将不同设备、移动应用程序和浏览器连接到后端服务。
在gRPC中,一个客户应用程序可以直接访问另外一台机器上的服务应用程序中的一个方法,就好像这个方法是一个本地对象一样,这种功能使得创建分布式应用程序和服务更加简单。和很多其他的RPC系统一样,gRPC是基于这样的思想:定义一个服务,指定一些方法,这些方法可以通过它的形式参数和返回值类型远程调用。在服务器端,服务器实现了这个接口,并且运行了一个gRPC的服务端去处理这些客户端调用。
springboot整合Grpc实现通讯的方法 - 图1
gRPC客户端和服务端在各种环境下都能相互通信,从google内部的服务器到你自己台式机上的服务器,而且可以使用gRPC支持的各种语言来实现gRPC客户端和服务器端。因此,你可以非常容易地创建一个用java语言写的gRPC服务器和一个用go语言或者Python语言或者Ruby语言写gRPC客户端。除此之外,最新的Google API也有gRPC版本的接口,这样用户可以非常方便的将Google的功能集成到自己的应用程序中。

使用场景

  • 在微服务架构中有效地连接多个服务
  • 将移动设备、浏览器客户端连接到后端服务
  • 生成高效的客户端库
  • 不同项目、产品之间的交互

    使用Protocol Buffers

    默认情况下,gRPC使用Protocol Buffers,这是Google的开源成熟序列化结构化数据的机制(不过,gRPC也可以和其他的数据格式一起使用,比如JSON)。这是一份关于如何使用Protocol Buffers的快速介绍。如果你已经对Protocol Buffers比较熟悉了,可以先跳到下一节。
    使用Protocol Buffers的第一步是在一个proto文件中定义你想要序列化的数据结构,Proto文件是一个扩展名为.proto的普通文本文件。Protocol Buffers数据是结构化为message的,一个message是一个小的逻辑信息单元,这个逻辑信息单元包含一系列的键值对,这些键值对被称为字段。这里有一个例子: ```java // The greeter service definition. service Greeter { // Sends a greeting rpc SayHello (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; }

  1. <a name="F7Zca"></a>
  2. # Springboot集成Grpc
  3. <a name="T0HUo"></a>
  4. ## 创建qingfeng-grpc项目
  5. 项目创建好之后,继续创建qingfeng-grpclib模块、qingfeng-server模块、qingfeng-client模块。<br />![image.png](https://cdn.nlark.com/yuque/0/2022/png/12591990/1651403439991-c2d7e4e6-8fd8-4bae-a6bc-542bc82be355.png#clientId=u3222c419-0fae-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=245&id=u3f5ec06c&margin=%5Bobject%20Object%5D&name=image.png&originHeight=294&originWidth=417&originalType=binary&ratio=1&rotation=0&showTitle=false&size=21335&status=done&style=none&taskId=u8ad85317-df23-49d5-8cfc-58d64b5050d&title=&width=347.4999861915912)<br />引入pom依赖
  6. ```java
  7. <?xml version="1.0" encoding="UTF-8"?>
  8. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  9. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  10. <modelVersion>4.0.0</modelVersion>
  11. <packaging>pom</packaging>
  12. <modules>
  13. <module>qingfeng-grpclib</module>
  14. <module>qingfeng-server</module>
  15. <module>qingfeng-client</module>
  16. <module>qingfeng-protobuf</module>
  17. </modules>
  18. <parent>
  19. <groupId>org.springframework.boot</groupId>
  20. <artifactId>spring-boot-starter-parent</artifactId>
  21. <version>2.1.4.RELEASE</version>
  22. <relativePath/>
  23. </parent>
  24. <groupId>com.qingfeng</groupId>
  25. <artifactId>qingfeng-grpc</artifactId>
  26. <version>1.0-SNAPSHOT</version>
  27. <name>qingfeng-grpc</name>
  28. <properties>
  29. <java.version>1.8</java.version>
  30. </properties>
  31. <dependencyManagement>
  32. <dependencies>
  33. <dependency>
  34. <groupId>com.com.qingfeng</groupId>
  35. <artifactId>com.qingfeng-grpclib</artifactId>
  36. <version>1.0-SNAPSHOT</version>
  37. </dependency>
  38. <!--核心grpc-spring-boot依赖-->
  39. <dependency>
  40. <groupId>net.devh</groupId>
  41. <artifactId>grpc-client-spring-boot-starter</artifactId>
  42. <version>2.0.1.RELEASE</version>
  43. </dependency>
  44. <dependency>
  45. <groupId>net.devh</groupId>
  46. <artifactId>grpc-server-spring-boot-starter</artifactId>
  47. <version>2.0.1.RELEASE</version>
  48. </dependency>
  49. </dependencies>
  50. </dependencyManagement>
  51. </project>

创建qingfeng-grpclib

引入pom依赖

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>qingfeng-grpc</artifactId>
  7. <groupId>com.qingfeng</groupId>
  8. <version>1.0-SNAPSHOT</version>
  9. </parent>
  10. <modelVersion>4.0.0</modelVersion>
  11. <groupId>com.qingfeng</groupId>
  12. <artifactId>qingfeng-grpclib</artifactId>
  13. <version>1.0-SNAPSHOT</version>
  14. <properties>
  15. <os.plugin.version>1.6.0</os.plugin.version>
  16. <grpc.version>1.15.1</grpc.version>
  17. <protoc.version>3.6.1</protoc.version>
  18. <protobuf.plugin.version>0.6.1</protobuf.plugin.version>
  19. </properties>
  20. <dependencies>
  21. <dependency>
  22. <groupId>io.grpc</groupId>
  23. <artifactId>grpc-all</artifactId>
  24. <version>${grpc.version}</version>
  25. </dependency>
  26. </dependencies>
  27. <build>
  28. <extensions>
  29. <extension>
  30. <groupId>kr.motd.maven</groupId>
  31. <artifactId>os-maven-plugin</artifactId>
  32. <version>${os.plugin.version}</version>
  33. </extension>
  34. </extensions>
  35. <plugins>
  36. <plugin>
  37. <groupId>org.xolstice.maven.plugins</groupId>
  38. <artifactId>protobuf-maven-plugin</artifactId>
  39. <version>${protobuf.plugin.version}</version>
  40. <extensions>true</extensions>
  41. <configuration>
  42. <protocArtifact>com.google.protobuf:protoc:${protoc.version}:exe:${os.detected.classifier}
  43. </protocArtifact>
  44. <pluginId>grpc-java</pluginId>
  45. <pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}
  46. </pluginArtifact>
  47. <!--默认值-->
  48. <protoSourceRoot>${project.basedir}/src/main/proto</protoSourceRoot>
  49. <!--默认值-->
  50. <!--<outputDirectory>${project.build.directory}/generated-sources/protobuf/java</outputDirectory>-->
  51. <outputDirectory>${project.basedir}/src/main/java</outputDirectory>
  52. <!--设置是否在生成java文件之前清空outputDirectory的文件,默认值为true,设置为false时也会覆盖同名文件-->
  53. <clearOutputDirectory>false</clearOutputDirectory>
  54. <!--更多配置信息可以查看https://www.xolstice.org/protobuf-maven-plugin/compile-mojo.html-->
  55. </configuration>
  56. <executions>
  57. <execution>
  58. <!--在执行mvn compile的时候会执行以下操作-->
  59. <phase>compile</phase>
  60. <goals>
  61. <!--生成OuterClass类-->
  62. <goal>compile</goal>
  63. <!--生成Grpc类-->
  64. <goal>compile-custom</goal>
  65. </goals>
  66. </execution>
  67. </executions>
  68. </plugin>
  69. </plugins>
  70. </build>
  71. </project>

在线构建protobuf代码

  1. <build>
  2. <extensions>
  3. <extension>
  4. <groupId>kr.motd.maven</groupId>
  5. <artifactId>os-maven-plugin</artifactId>
  6. <version>${os.plugin.version}</version>
  7. </extension>
  8. </extensions>
  9. <plugins>
  10. <plugin>
  11. <groupId>org.xolstice.maven.plugins</groupId>
  12. <artifactId>protobuf-maven-plugin</artifactId>
  13. <version>${protobuf.plugin.version}</version>
  14. <extensions>true</extensions>
  15. <configuration>
  16. <protocArtifact>com.google.protobuf:protoc:${protoc.version}:exe:${os.detected.classifier}
  17. </protocArtifact>
  18. <pluginId>grpc-java</pluginId>
  19. <pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}
  20. </pluginArtifact>
  21. <!--默认值-->
  22. <protoSourceRoot>${project.basedir}/src/main/proto</protoSourceRoot>
  23. <!--默认值-->
  24. <!--<outputDirectory>${project.build.directory}/generated-sources/protobuf/java</outputDirectory>-->
  25. <outputDirectory>${project.basedir}/src/main/java</outputDirectory>
  26. <!--设置是否在生成java文件之前清空outputDirectory的文件,默认值为true,设置为false时也会覆盖同名文件-->
  27. <clearOutputDirectory>false</clearOutputDirectory>
  28. <!--更多配置信息可以查看https://www.xolstice.org/protobuf-maven-plugin/compile-mojo.html-->
  29. </configuration>
  30. <executions>
  31. <execution>
  32. <!--在执行mvn compile的时候会执行以下操作-->
  33. <phase>compile</phase>
  34. <goals>
  35. <!--生成OuterClass类-->
  36. <goal>compile</goal>
  37. <!--生成Grpc类-->
  38. <goal>compile-custom</goal>
  39. </goals>
  40. </execution>
  41. </executions>
  42. </plugin>
  43. </plugins>
  44. </build>

创建Greeter.proto

  1. syntax = "proto3";
  2. option java_package = "com.qingfeng.grpc.lib";
  3. // The greeting service definition.
  4. service Greeter{
  5. // Sends a greeting
  6. rpc SayHello (HelloRequest) returns (HelloReply) {
  7. }
  8. }
  9. // The request message containing the user's name.
  10. message HelloRequest {
  11. string name = 1;
  12. }
  13. // The response message containing the greetings
  14. message HelloReply {
  15. string message = 1;
  16. }

执行maven compile 编译
image.png

创建qingfeng-server服务端

引入pom依赖

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>qingfeng-grpc</artifactId>
  7. <groupId>com.qingfeng</groupId>
  8. <version>1.0-SNAPSHOT</version>
  9. </parent>
  10. <modelVersion>4.0.0</modelVersion>
  11. <artifactId>qingfeng-server</artifactId>
  12. <properties>
  13. <java.version>1.8</java.version>
  14. </properties>
  15. <dependencies>
  16. <dependency>
  17. <groupId>com.qingfeng</groupId>
  18. <artifactId>qingfeng-grpclib</artifactId>
  19. <version>1.0-SNAPSHOT</version>
  20. </dependency>
  21. <dependency>
  22. <groupId>org.springframework.boot</groupId>
  23. <artifactId>spring-boot-starter</artifactId>
  24. </dependency>
  25. <dependency>
  26. <groupId>org.springframework.boot</groupId>
  27. <artifactId>spring-boot-starter-test</artifactId>
  28. <scope>test</scope>
  29. </dependency>
  30. <dependency>
  31. <groupId>org.projectlombok</groupId>
  32. <artifactId>lombok</artifactId>
  33. </dependency>
  34. <dependency>
  35. <groupId>net.devh</groupId>
  36. <artifactId>grpc-server-spring-boot-starter</artifactId>
  37. </dependency>
  38. </dependencies>
  39. </project>

创建application.yml

  1. spring:
  2. application:
  3. name: qingfeng-server
  4. grpc:
  5. server:
  6. port: 9000
  7. server:
  8. port: 9002

创建GreeterService

  1. package com.qingfeng.service;
  2. import com.qingfeng.grpc.lib.GreeterGrpc;
  3. import com.qingfeng.grpc.lib.GreeterOuterClass;
  4. import io.grpc.stub.StreamObserver;
  5. import lombok.extern.slf4j.Slf4j;
  6. import net.devh.springboot.autoconfigure.grpc.server.GrpcService;
  7. @Slf4j
  8. @GrpcService(GreeterOuterClass.class)
  9. public class GreeterService extends GreeterGrpc.GreeterImplBase {
  10. @Override
  11. public void sayHello(GreeterOuterClass.HelloRequest request, StreamObserver<GreeterOuterClass.HelloReply> responseObserver) {
  12. String message = "Hello " + request.getName();
  13. final GreeterOuterClass.HelloReply.Builder replyBuilder = GreeterOuterClass.HelloReply.newBuilder().setMessage(message);
  14. responseObserver.onNext(replyBuilder.build());
  15. responseObserver.onCompleted();
  16. log.info("Returning " + message);
  17. }
  18. }

完成后-启动服务

image.png

创建qingfeng-client客户端

引入pom依赖

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>qingfeng-grpc</artifactId>
  7. <groupId>com.qingfeng</groupId>
  8. <version>1.0-SNAPSHOT</version>
  9. </parent>
  10. <modelVersion>4.0.0</modelVersion>
  11. <artifactId>qingfeng-client</artifactId>
  12. <properties>
  13. <java.version>1.8</java.version>
  14. </properties>
  15. <dependencies>
  16. <dependency>
  17. <groupId>com.qingfeng</groupId>
  18. <artifactId>qingfeng-grpclib</artifactId>
  19. <version>1.0-SNAPSHOT</version>
  20. </dependency>
  21. <dependency>
  22. <groupId>org.springframework.boot</groupId>
  23. <artifactId>spring-boot-starter</artifactId>
  24. </dependency>
  25. <dependency>
  26. <groupId>org.springframework.boot</groupId>
  27. <artifactId>spring-boot-starter-test</artifactId>
  28. <scope>test</scope>
  29. </dependency>
  30. <dependency>
  31. <groupId>org.springframework.boot</groupId>
  32. <artifactId>spring-boot-starter-web</artifactId>
  33. </dependency>
  34. <dependency>
  35. <groupId>net.devh</groupId>
  36. <artifactId>grpc-client-spring-boot-starter</artifactId>
  37. </dependency>
  38. <dependency>
  39. <groupId>org.springframework.boot</groupId>
  40. <artifactId>spring-boot-starter-web</artifactId>
  41. </dependency>
  42. <dependency>
  43. <groupId>org.projectlombok</groupId>
  44. <artifactId>lombok</artifactId>
  45. </dependency>
  46. </dependencies>
  47. </project>

创建application.yml

  1. server:
  2. port: 9001
  3. spring:
  4. application:
  5. name: qingfeng-client
  6. grpc:
  7. client:
  8. qingfeng-server:
  9. port: 9000
  10. enableKeepAlive: true
  11. keepAliveWithoutCalls: true

创建GrpcClientService

  1. package com.qingfeng.service;
  2. import com.qingfeng.grpc.lib.GreeterGrpc;
  3. import com.qingfeng.grpc.lib.GreeterOuterClass;
  4. import com.qingfeng.grpc.lib.InterruptGrpc;
  5. import com.qingfeng.grpc.lib.InterruptStatus;
  6. import io.grpc.Channel;
  7. import io.grpc.netty.NegotiationType;
  8. import io.grpc.netty.NettyChannelBuilder;
  9. import net.devh.springboot.autoconfigure.grpc.client.GrpcClient;
  10. import org.springframework.beans.BeanUtils;
  11. import org.springframework.beans.factory.annotation.Value;
  12. import org.springframework.stereotype.Service;
  13. import java.util.ArrayList;
  14. import java.util.List;
  15. import java.util.Objects;
  16. @Service
  17. public class GrpcClientService {
  18. @GrpcClient("qingfeng-server")
  19. private Channel serverChannel;
  20. public String sendMessage(String name) {
  21. GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(serverChannel);
  22. GreeterOuterClass.HelloReply response = stub.sayHello(GreeterOuterClass.HelloRequest.newBuilder().setName(name).build());
  23. return response.getMessage();
  24. }
  25. }

创建GrpcClientController

  1. @RestController
  2. public class GrpcClientController {
  3. @Autowired
  4. private GrpcClientService grpcClientService;
  5. @RequestMapping("/")
  6. public String printMessage(@RequestParam(defaultValue = "青锋") String name) {
  7. return grpcClientService.sendMessage(name);
  8. }
  9. }

完成后-启动客户端测试

image.png
在浏览器输入 http://localhost:9001/
image.png