在查找protobuf相关资料时看到了grpc这个google开源的rpc框架,正好自己查protobuf就是想用protobuf和netty实现一个简单的rpc通信,既然发现了grpc,那肯定得安排搞上一搞
先去grpc的官网黄了一圈,大概的查看了一下相关的说明和Quick start,然后按照grpc-java项目的README.md开始了使用,这里记录下自己的大概步骤和遇到的一些小问题
- 引入相关依赖
因为我用的JDK8,所以只有下面这几个依赖
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty-shaded</artifactId>
<version>1.39.0</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>1.39.0</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>1.39.0</version>
</dependency>
- 添加build插件
<build>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.6.2</version>
</extension>
</extensions>
<plugins>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.6.1</version>
<configuration>
<protocArtifact>com.google.protobuf:protoc:3.17.2:exe:${os.detected.classifier}</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:1.39.0:exe:${os.detected.classifier}</pluginArtifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
这两步都跟官方一致,没啥好说的,按部就班即可
- 编写proto文件
proto文件需要放在/src/main/proto目录下
syntax = "proto3";
import "google/protobuf/empty.proto";
import "google/protobuf/wrappers.proto";
option java_multiple_files = true;
option java_package = "com.fan.xc.boot.plugins.weixin.grpc";
option java_outer_classname = "WeiXinProto";
service WeiXinService {
// 获取accessToken
rpc getAccessToken(google.protobuf.Empty) returns (google.protobuf.StringValue) {
}
// 获取accessToken
rpc getJsTicket(google.protobuf.Empty) returns (google.protobuf.StringValue) {
}
}
这里遇到一个小问题,就是rpc的定义里面,不管有没有入参,都需要设置一个message,没有参数的话,可以使用Empty,单个参数的话,也需要使用message定义,可以使用google预定义好的message,就是返回那里写的StringValue,Empty和StringValue都是在proto文件开始的地方用import引入的
- 生成java文件
mvn clean compile
执行maven的compile命令,就会在target目录下生成对应的java文件了,将其异动到source目录下对应的包中即可
至此准备工作都做完了,接下来就是编写相关代码了
- 实现grpc的server
package com.fan.xc.boot.plugins.weixin.grpc
import com.alibaba.fastjson.JSON
import com.fan.xc.boot.plugins.weixin.AccessTokenManager
import com.fan.xc.boot.plugins.weixin.JsApiTicketManager
import com.fan.xc.boot.plugins.weixin.WeiXinConfig
import com.fan.xc.boot.plugins.weixin.grpc.WeiXinServiceGrpc.WeiXinServiceImplBase
import com.google.protobuf.Empty
import com.google.protobuf.StringValue
import io.grpc.ServerBuilder
import io.grpc.stub.StreamObserver
import org.springframework.beans.factory.InitializingBean
/**
* 实现grpc Server
* @author fan
*/
class WeiXinRpcServer(private val config: WeiXinConfig,
private val accessTokenManager: AccessTokenManager,
private val jsApiTicketManager: JsApiTicketManager)
: WeiXinServiceImplBase(), InitializingBean {
/**
* 获取access token
*/
override fun getAccessToken(request: Empty, responseObserver: StreamObserver<StringValue>) {
val json = JSON.toJSONString(mapOf("code" to 0, "access_token" to accessTokenManager.token(), "expires" to accessTokenManager.expires()))
val stringValue = StringValue.newBuilder().setValue(json).build()
responseObserver.onNext(stringValue)
responseObserver.onCompleted()
}
/**
* 获取js ticket
*/
override fun getJsTicket(request: Empty, responseObserver: StreamObserver<StringValue>) {
val json = JSON.toJSONString(mapOf("code" to 0, "ticket" to jsApiTicketManager.token(), "expires" to jsApiTicketManager.expires()))
val stringValue = StringValue.newBuilder().setValue(json).build()
responseObserver.onNext(stringValue)
responseObserver.onCompleted()
}
override fun afterPropertiesSet() {
val server = config.server
if (server?.isEnable == true) {
// 开启server
ServerBuilder.forPort(server.port).addService(this)
.build().start()
}
}
}
简单来说就是继承xxxServiceImplBase,重写对应的方法
afterPropertiesSet方法是为了在服务启动时启动grpc的server
- 实现客户端
package com.fan.xc.boot.plugins.weixin.grpc
import com.fan.xc.boot.plugins.weixin.WeiXinConfig
import com.google.protobuf.Empty
import io.grpc.ManagedChannelBuilder
class WeiXinRpcClient(private val config: WeiXinConfig) {
private val stub: WeiXinServiceGrpc.WeiXinServiceBlockingStub by lazy {
val client = config.client
val server = config.server
// 如果打开了server, 就一定不允许配置client
return@lazy if (server?.isEnable != true && client?.isEnable == true) {
val host = client.host ?: throw IllegalArgumentException("weixin.client.host error")
val port = client.port
if (port <= 0 || port >= 65535) {
throw IllegalArgumentException("weixin.client.port error")
}
val channel = ManagedChannelBuilder.forAddress(host, port)
.usePlaintext().build()
WeiXinServiceGrpc.newBlockingStub(channel)
} else throw IllegalStateException("init weixin rpc client failed")
}
fun getAccessToken(): String {
val token = stub.getAccessToken(Empty.getDefaultInstance())
return token.value
}
fun getJsTicket(): String {
val token = stub.getJsTicket(Empty.getDefaultInstance())
return token.value
}
}
客户端的实现比较简单,延迟生成stub,然后就是正常的方法调用,注意下传参即可
相关的代码都在这儿