gRPC系列文章 SpringBoot下的HelloWorld

gRPC系列文章 SpringBoot下的HelloWorld

SpringBoot下的gRPC相比较C++下的要容易多了,只要把gRPC相关依赖和protobuf插件引入,剩下的就是点击鼠标了。

环境

  • Idea 2018.3
  • Windows 7
  • SpringBoot 2.1.2
  • Gradle 4.8

示例项目仓库

build.gradle配置

首先是引入protobuf gradle插件用来编译proto

plugins {
    id 'org.springframework.boot' version '2.1.2.RELEASE'
    id 'java'
    // ASSUMES GRADLE 2.12 OR HIGHER. Use plugin version 0.7.5 with earlier gradle versions
    id 'com.google.protobuf' version '0.8.8'
    // Generate IntelliJ IDEA's .idea & .iml project files
    id 'idea'
}

定义grpc、protobuf的版本号变量

// updating the version in our release process.
def grpcVersion = '1.27.0' // CURRENT_GRPC_VERSION
def protobufVersion = '3.11.2'
def protobufJavaUtilVersion = '3.11.3'
def protocVersion = protobufVersion

引入gRPC项目的基础依赖

    implementation "io.grpc:grpc-protobuf:${grpcVersion}"
    implementation "io.grpc:grpc-stub:${grpcVersion}"
    compileOnly "javax.annotation:javax.annotation-api:1.2"

    // examples/advanced need this for JsonFormat
    implementation "com.google.protobuf:protobuf-java-util:${protobufJavaUtilVersion}"

    runtimeOnly "io.grpc:grpc-netty-shaded:${grpcVersion}"

    testImplementation "io.grpc:grpc-testing:${grpcVersion}"

配置protobuf gradle插件

protobuf {
    protoc { artifact = "com.google.protobuf:protoc:${protocVersion}" }
    plugins {
        grpc { artifact = "io.grpc:protoc-gen-grpc-java:${grpcVersion}" }
    }
    generateProtoTasks {
        all()*.plugins { grpc {} }
    }
}

默认情况下protobuf从\src\main\proto路径下查找proto。

配置结束后refresh一下gradle

在这里插入图片描述

此外,建议大家用Idea的话最好装上proto文件的插件,方便编辑proto
在这里插入图片描述

编译helloworld.proto

在这里插入图片描述
在这里插入图片描述
把生成的类拿到项目中使用。

测试

启动Server
在这里插入图片描述
启动Client
在这里插入图片描述
Client终端输出
在这里插入图片描述

现在试试用java的client调用C++的server端:

不要忘了关闭java的server端啊。

首先运行C++的server
在这里插入图片描述
运行java的client
在这里插入图片描述
Java终端输出
在这里插入图片描述


gRPC文章系列

gRPC系列文章 RPC概念、数据传输协议、序列化协议

gRPC系列文章 gRPC++项目生成、编译

gRPC系列文章 gRPC++ HelloWorld项目

发布了54 篇原创文章 · 获赞 9 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/wangxudongx/article/details/104235803