一. 简介gRpc
1.gRpc简介
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 Server主要完成以下功能: 将proto中定义的service的真正实现注册到grpc的Server中。 管理Server的Socket以及在Socket上传输数据的过程。
具体的介绍请参考 gRpc中文文档
http://doc.oschina.net/grpc?t=58009
二. 项目结构
1.项目结构
(1) 创建maven项目主模块pop.xml
(2) grpc-server模块 RPC服务端
(3)lib-server模块 RPC接口 包含原始proto文件,并负责将其转换为java代码
(4) grpc-client模块 RPC客户端
2.模块关系
相互关系 根项目负责依赖版本管理,grpc-server和grpc-client都依赖grpc-lib的接口,其中,grpc-server提供了接口的具体实现,而grpc-client则调用了grpc-server的实现,他们通过grpc-lib来确定使用规范(接口即契约) 对应MVC关系 grpc-lib就是service(接口,为提供实现) grpc-server就相当于serviceImpl(service的实现类) grpc-client就是controller的角色. 框架依赖 grpc-lib需要将proto文件转换成java类,故需依赖于protobuf-maven-plugin插件,另外还需要io.grpc下的grpc-all,否则生成的java类会提示缺少依赖 grpc-server 负责提供rpc服务,不需要spring-web支持 grpc-client 调用rpc服务
三. 创建项目
按照多模块结构进行创建
创建主项目pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.li</groupId>
<artifactId>springboot-grpc</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<modules>
<module>grpc-server</module>
<module>lib-server</module>
</modules>
<properties>
<java.version>1.8</java.version>
<os.plugin.version>1.6.0</os.plugin.version>
<grpc.version>1.15.1</grpc.version>
<protoc.version>3.6.1</protoc.version>
<protobuf.plugin.version>0.6.1</protobuf.plugin.version>
<net-devh-grpc.version>2.0.1.RELEASE</net-devh-grpc.version>
</properties>
<packaging>pom</packaging>
<dependencies>
<!--公共grpc模块-->
<dependency>
<groupId>com.li</groupId>
<artifactId>lib-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<!--核心grpc-spring-boot依赖-->
<dependency>
<groupId>net.devh</groupId>
<artifactId>grpc-client-spring-boot-starter</artifactId>
<version>${net-devh-grpc.version}</version>
</dependency>
<dependency>
<groupId>net.devh</groupId>
<artifactId>grpc-server-spring-boot-starter</artifactId>
<version>${net-devh-grpc.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
</project>
2.创建grpc-lib模块
(1) 创建之前要安装插件Protobuf Support
然后创建maven管理的java项目,pom文件如下 proto文件目录是${project.basedir}/src/main/proto 生成的java代码在${project.basedir}/src/main/java
文件夹自行创建
使用maven指令compile可完成代码生成,或直接在IDE里用proto插件运行compile和compile-custom
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.li</groupId>
<artifactId>springboot-grpc</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>lib-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>lib-server</name>
<description>Demo project for Spring Boot</description>
<packaging>jar</packaging>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-all</artifactId>
<version>${grpc.version}</version>
</dependency>
</dependencies>
<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>
<extensions>true</extensions>
<configuration>
<protocArtifact>com.google.protobuf:protoc:${protoc.version}:exe:${os.detected.classifier}</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact>
<!--默认值-->
<protoSourceRoot>${project.basedir}/src/main/proto</protoSourceRoot>
<!--默认值-->
<!--<outputDirectory>${project.build.directory}/generated-sources/protobuf/java</outputDirectory>-->
<outputDirectory>${project.basedir}/src/main/java</outputDirectory>
<!--设置是否在生成java文件之前清空outputDirectory的文件,默认值为true,设置为false时也会覆盖同名文件-->
<clearOutputDirectory>false</clearOutputDirectory>
<!--更多配置信息可以查看https://www.xolstice.org/protobuf-maven-plugin/compile-mojo.html-->
</configuration>
<executions>
<execution>
<!--在执行mvn compile的时候会执行以下操作-->
<phase>compile</phase>
<goals>
<!--生成OuterClass类-->
<goal>compile</goal>
<!--生成Grpc类-->
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
(2) 在grpc-lib模块利用proto文件生成java代码syntax = "proto3";
option java_package = "com.li.libserver";
// 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;
}
(3) 生成代码 使用maven的complie即可
3.创建grpc-server模块实现接口
(1) 首先在application.yml文件指定应用名和grpc端口,如下
spring.application.name= local-grpc-server
grpc.server.port=9898
(2) 创建GreeterService服务类
package com.li.grpcserver;
import com.li.libserver.GreeterGrpc;
import com.li.libserver.GreeterOuterClass;
import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;
import net.devh.springboot.autoconfigure.grpc.server.GrpcService;
@Slf4j
@GrpcService(GreeterOuterClass.class)
public class GreeterService extends GreeterGrpc.GreeterImplBase{
@Override
public void sayHello(GreeterOuterClass.HelloRequest request, StreamObserver<GreeterOuterClass.HelloReply> responseObserver) {
String message = "Hello " + request.getName();
final GreeterOuterClass.HelloReply.Builder replyBuilder = GreeterOuterClass.HelloReply.newBuilder().setMessage(message);
responseObserver.onNext(replyBuilder.build());
responseObserver.onCompleted();
log.info("Returning " +message);
}
}
4.在grpc-client模块调用服务
(1) grpc需要开放接口,故需在application.yml指定端口,另外还需指定grpc-server地址和端口,这里将grpc-server的地址以环境变量的方式开放出来,默认在本地。yml文件如下
server.port=8088
spring.application.name= local-grpc-client
grpc.client.local-grpc-server.host=${LOCAL-GRPC-HOST:127.0.0.1}
grpc.client.local-grpc-server.port=9898
grpc.client.local-grpc-server.enableKeepAlive= true
grpc.client.local-grpc-server.keepAliveWithoutCalls=true
(2) 创建GrpcClientService服务类
package com.li.grpcclient;
import com.li.libserver.GreeterGrpc;
import com.li.libserver.GreeterOuterClass;
import io.grpc.Channel;
import lombok.extern.slf4j.Slf4j;
import net.devh.springboot.autoconfigure.grpc.client.GrpcClient;
import org.springframework.stereotype.Service;
@Service
public class GrpcClientService {
@GrpcClient("local-grpc-server")
private Channel serverChannel;
String sendMessage(String name) {
GreeterGrpc.GreeterBlockingStub stub= GreeterGrpc.newBlockingStub(serverChannel);
GreeterOuterClass.HelloReply response = stub.sayHello(GreeterOuterClass.HelloRequest.newBuilder().setName(name).build());
return response.getMessage();
}
}
(3) 创建GrpcClientController类
package com.li.grpcclient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GrpcClientController {
@Autowired
private GrpcClientService grpcClientService;
@RequestMapping("/")
public String printMessage(String name) {
return grpcClientService.sendMessage(name);
}
}
四. 项目启动并测试
依次启动grpc-server和grpc-client,打开http://localhost:8088/?name=li即可看到结果
同时grpc-server项目日志输出如下
2019-03-03 20:39:19.297 INFO 5912 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2019-03-03 20:39:19.298 INFO 5912 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2019-03-03 20:39:19.321 INFO 5912 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 23 ms
Returning Hello li
以上就是Spring Boot整合gRpc的简单项目,其他东西可以在官网进行学习
源码下载:https://github.com/LiHaodong888/SpringBootLearn
未经允许不得转载