1、前言
在微服务开发中,服务间的调用一般有两种方式:Feign、RestTemplate,但在实际使用过程中,尤其是Feign,存在各种限制及局限性,如:HTTP请求方式、返回类型等限制,有时会让你觉得那那都别扭。在微服务项目中,服务间的调用,是非常普遍频繁的,其性能也不是很理想。
为了解决上述问题,进行反复对比,最终服务间的调用方式采取了gRPC方式,其显著特点就是性能之高(通信采用Netty),通过proto文件定义的接口也是非常清晰而又灵活。本文主要就gRPC在Spring Cloud项目中的使用进行说明实战。
关于gRPC相关基础知识可以参考上一篇文章gRPC的使用。
2、gRPC在Spring Cloud中的使用
看过上一篇文章gRPC的使用的话,你就清楚如果直接使用gRPC,显得有些吃力,因此借助一些开源的框架变得尤为必要。gRPC在Spring Cloud中使用开源项目grpc-spring-boot-starter,便于在Spring Cloud项目中开发应用。
(grpc-spring-boot-starter虽然存在一些问题,但集成Sping Cloud项目已经相当高了,还是不错之选。如果你有时间,精力,还是又必要在源码基础上进行开发。)
下面以实际demo来说明grpc-spring-boot-starter的应用。
2.1 特点
使用@ GrpcService自动创建并运行一个 gRPC 服务,内嵌在 spring-boot 应用中
使用@ GrpcClient自动创建和管理你的客户端
支持Spring Cloud(向Consul或Eureka注册服务并获取gRPC服务器信息)
支持Spring Sleuth 进行链路跟踪
支持对于server、client 分别设置全局拦截器或单个的拦截器
支持Spring-Security
支持metric (micrometer / actuator)
(看了上面这些特点,就知道为啥选择这个开源项目了)
2.2 使用DEMO
2.2.1 定义gRPC接口
基于protobuf来声明数据模型和RPC接口服务。
创建一个公共字模块项目spring-boot-grpc-common,用于定义存放gRPC接口(proto),便于gRPC服务端和客户端使用。以helloworld.proto(src\main\proto\helloworld.proto)为例:
syntax = "proto3";
option java_multiple_files = true;
option java_package = "com.xcbeyond.springboot.grpc.lib";
option java_outer_classname = "HelloWorldProto";
// The greeting service definition.
service Simple {
// 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;
}
根据proto的命令可以转换成对应的语言的代码,生成java代码,也可以借助maven插件,在编译时自动生成。这里通过mavent插件,可以在pom.xml中增加如下依赖:
<build>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>${os.plugin.version}</version>
</extension>
</extensions>
<plugins>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>${protobuf.plugin.version}</version>
<configuration>
<protocArtifact>com.google.protobuf:protoc:${protoc.version}:exe:${os.detected.classifier}</protocArtifact>