Spring Boot 2+gRPC 学习系列1:搭建Spring Boot 2+gRPC本地项目

本项目基于Spring Boot 2.0.5+yidongnan/grpc-spring-boot-starter 2.0.1.RELEASE,通过grpc-lib,grpc-server,grpc-client 3个模块来模拟grpc的服务调用。

主要参考自yidongnan/grpc-spring-boot-starter和LogNet/grpc-spring-boot-starter的官方example
yidongnan项目的主要优点有:项目使用maven和gradle两种方式,grpc-client连接grpc-server的channel通过注解自动注入,较优雅。缺点是文档没LogNet的丰富。两者功能相近,所以我使用了yidognnan的starter。

本项目已上传至GitHub:https://github.com/linshenkx/grpc-springboot-lin

文章目录

    • 一 项目结构
      • 1 项目结构
      • 2 模块功能
    • 二 项目搭建
      • 0 编写根项目pom文件
      • 1 创建grpc-lib模块
      • 2 创建grpc-server模块
      • 3 创建grpc-client模块
    • 三 功能实现
      • 1 在grpc-lib模块利用proto文件生成java代码
        • (1) 编写proto文件
        • (2) 生成java代码
      • 2 在grpc-server模块实现接口
        • (1) 编写application文件
        • (2) 编写GreeterService类
      • 3 在grpc-client模块调用服务
        • (1) 编写application文件
        • (2)编写GrpcClientService服务类
        • (3)编写GrpcClientController类
    • 四 项目启动并测试
    • 五 其他

一 项目结构

1 项目结构

根项目(com.linshen:grpc-springboot-lin:1.0-SNAPSHOT)下有3个子模块:

  • grpc-lib:包含原始proto文件,并负责将其转换为java代码
  • grpc-server:grpc服务端
  • grpc-client : grpc客户端

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服务

二 项目搭建

0 编写根项目pom文件

如下,根项目主要负责定义项目子模块,全局属性和版本管理


<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.0modelVersion>

    <groupId>com.linshengroupId>
    <artifactId>grpc-springboot-linartifactId>
    <version>1.0-SNAPSHOTversion>
    <packaging>pompackaging>

    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.0.5.RELEASEversion>
    parent>

    
    <modules>
        <module>grpc-libmodule>
        <module>grpc-servermodule>
        <module>grpc-clientmodule>
    modules>

    <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
        <java.version>1.8java.version>
        <spring-boot.version>2.0.5.RELEASEspring-boot.version>
        <net-devh-grpc.version>2.0.1.RELEASEnet-devh-grpc.version>

    properties>

    <dependencyManagement>
        <dependencies>
            
            <dependency>
                <groupId>io.spring.platformgroupId>
                <artifactId>platform-bomartifactId>
                <version>Cairo-RELEASEversion>
                <type>pomtype>
                <scope>importscope>
            dependency>
            
            <dependency>
                <groupId>com.linshengroupId>
                <artifactId>grpc-libartifactId>
                <version>${project.version}version>
            dependency>
            
            <dependency>
                <groupId>net.devhgroupId>
                <artifactId>grpc-client-spring-boot-starterartifactId>
                <version>${net-devh-grpc.version}version>
            dependency>
            <dependency>
                <groupId>net.devhgroupId>
                <artifactId>grpc-server-spring-boot-starterartifactId>
                <version>${net-devh-grpc.version}version>
            dependency>
        dependencies>
    dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-deploy-pluginartifactId>
                <configuration>
                    <skip>trueskip>
                configuration>
            plugin>
        plugins>
    build>

project>

1 创建grpc-lib模块

创建maven管理的java项目,pom文件如下
proto文件目录是${project.basedir}/src/main/proto
生成的java代码在${project.basedir}/src/main/java
使用maven指令compile可完成代码生成,或直接在IDE里用proto插件运行compilecompile-custom


<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.0modelVersion>

    <artifactId>grpc-libartifactId>
    <packaging>jarpackaging>

    <name>grpc-libname>

    <parent>
        <groupId>com.linshengroupId>
        <artifactId>grpc-springboot-linartifactId>
        <version>1.0-SNAPSHOTversion>
    parent>

    <properties>
        <os.plugin.version>1.6.0os.plugin.version>
        <grpc.version>1.15.1grpc.version>
        <protoc.version>3.6.1protoc.version>
        <protobuf.plugin.version>0.6.1protobuf.plugin.version>
    properties>

    <dependencies>
        <dependency>
            <groupId>io.grpcgroupId>
            <artifactId>grpc-allartifactId>
            <version>${grpc.version}version>
        dependency>
    dependencies>

    <build>
        <extensions>
            <extension>
                <groupId>kr.motd.mavengroupId>
                <artifactId>os-maven-pluginartifactId>
                <version>${os.plugin.version}version>
            extension>
        extensions>
        <plugins>
            <plugin>
                <groupId>org.xolstice.maven.pluginsgroupId>
                <artifactId>protobuf-maven-pluginartifactId>
                <version>${protobuf.plugin.version}version>
                <extensions>trueextensions>
                <configuration>
                    <protocArtifact>com.google.protobuf:protoc:${protoc.version}:exe:${os.detected.classifier}protocArtifact>
                    <pluginId>grpc-javapluginId>
                    <pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}pluginArtifact>
                    
                    <protoSourceRoot>${project.basedir}/src/main/protoprotoSourceRoot>
                    
                    
                    <outputDirectory>${project.basedir}/src/main/javaoutputDirectory>
                    
                    <clearOutputDirectory>falseclearOutputDirectory>
                    
                configuration>
                <executions>
                    <execution>
                        
                        <phase>compilephase>
                        <goals>
                            
                            <goal>compilegoal>
                            
                            <goal>compile-customgoal>
                        goals>
                    execution>
                executions>
            plugin>
        plugins>
    build>

project>

2 创建grpc-server模块


<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.0modelVersion>

    <artifactId>grpc-serverartifactId>
    <packaging>jarpackaging>

    <name>grpc-servername>

    <parent>
        <groupId>com.linshengroupId>
        <artifactId>grpc-springboot-linartifactId>
        <version>1.0-SNAPSHOTversion>
    parent>

    <dependencies>
        <dependency>
            <groupId>com.linshengroupId>
            <artifactId>grpc-libartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starterartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
        dependency>
        <dependency>
            <groupId>net.devhgroupId>
            <artifactId>grpc-server-spring-boot-starterartifactId>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>  
project>

3 创建grpc-client模块

可以看到,这里比grpc-server多了spring-web依赖


<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.0modelVersion>

    <artifactId>grpc-clientartifactId>
    <packaging>jarpackaging>

    <name>grpc-clientname>

    <parent>
        <groupId>com.linshengroupId>
        <artifactId>grpc-springboot-linartifactId>
        <version>1.0-SNAPSHOTversion>
    parent>

    <dependencies>
        <dependency>
            <groupId>com.linshengroupId>
            <artifactId>grpc-libartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>

        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
        dependency>
        <dependency>
            <groupId>net.devhgroupId>
            <artifactId>grpc-client-spring-boot-starterartifactId>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>

project>

三 功能实现

1 在grpc-lib模块利用proto文件生成java代码

(1) 编写proto文件

这里用的greeter.proto内容如下

syntax = "proto3";

option java_package = "com.linshen.grpc.lib";

// 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;
}

(2) 生成java代码

根据上文pom文件的设置,将proto文件放到src/main/proto目录下,运行protobuf插件的compile和compile-custom功能,生成java代码到src/main/java目录下。
生成后文件目录如下
Spring Boot 2+gRPC 学习系列1:搭建Spring Boot 2+gRPC本地项目_第1张图片

2 在grpc-server模块实现接口

(1) 编写application文件

首先在application.yml文件指定应用名和grpc端口,如下

spring:
  application:
    name: local-grpc-server
grpc:
  server:
    port: 9898

(2) 编写GreeterService类

@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);
    }
}

3 在grpc-client模块调用服务

(1) 编写application文件

grpc需要开放接口,故需在application.yml指定端口,另外还需指定grpc-server地址和端口,这里将grpc-server的地址以环境变量的方式开放出来,默认在本地。yml文件如下

server:
  port: 9090
spring:
  application:
    name: local-grpc-client
grpc:
  client:
    local-grpc-server:
      host:
      - ${LOCAL-GRPC-HOST:127.0.0.1}
      port:
      - 9898
      enableKeepAlive: true
      keepAliveWithoutCalls: true

(2)编写GrpcClientService服务类

注意,@GrpcClient根据value将yml文件里的配置绑定到Channel

@Service
public class GrpcClientService {

    @GrpcClient("local-grpc-server")
    private Channel serverChannel;

    public 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类

@RestController
public class GrpcClientController {

    @Autowired
    private GrpcClientService grpcClientService;

    @RequestMapping("/")
    public String printMessage(@RequestParam(defaultValue = "Michael") String name) {
        return grpcClientService.sendMessage(name);
    }
}

四 项目启动并测试

依次启动grpc-server和grpc-client,打开http://localhost:8080/或http://localhost:8080/?name=lin即可看到结果
在这里插入图片描述
同时grpc-server项目日志输出如下
在这里插入图片描述

需要注意的是,如果想要执行插件的jar打包,run启动等命令,需要先在根项目下运行mvn install,注意不是mvn install-install,否则会出现·Failed to collect dependencies·问题

五 其他

gRPC-Java指导:https://grpc.io/docs/tutorials/basic/java.html
gRPC-Java的GitHub地址:https://github.com/grpc/grpc-java
yidongnan/grpc-spring-boot-starter的GitHub地址:https://github.com/yidongnan/grpc-spring-boot-starter
LogNet/grpc-spring-boot-starter的GitHub地址:https://github.com/LogNet/grpc-spring-boot-starter
gRPC 官方文档中文版1.0:https://doc.oschina.net/grpc
Maven Protocol Buffers Plugin 插件指南:https://www.xolstice.org/protobuf-maven-plugin/index.html

你可能感兴趣的:(SpringBoot,RPC)