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终端输出