什么是 gRPCurl
gRPCurl 是一个命令行工具,用于与 gRPC 服务进行交互,可以算是 curl 的 gRPC 版本。由于 gRPC 服务之间的通信使用的是 protocol buffers 格式的二进制编码,所以无法使用传统的 curl ,为了更好上手,该工具和服务器交互时我们只需要提供 JSON 数据作为请求数据即可,该工具底层会自动将其编码为 PB 格式的二进制与服务端进行交互
该工具支持通过以下几种情况查看 gPRC service 的定义格式(schema):
- 通过 反射服务 进行查询
- 通过
proto源文件 - 通过编译完成的
protoset文件
只有通过使用上述方式查询得到的 schema,该工具才能能够将 JSON 请求数据准确的转换成 PB 格式的二进制数据,grpcurl 同时可以作为 lib 使用。这个 lib 提供了比其他工具更加简化的寻址功能
特点
grpcurl支持所有gRPC的方法,包括stream方法。通过grpcurl甚至可以与服务端进行双向的stream交流grpcurl支持plain-text(HTTP/2)及TLS, 对于TLS有大量的可选项配置,同时支持双向TLS即当客户端被要求提交证书也是支持的grpcurl支持通过反射服务无缝连接,又或者使用proto或则protoset文件
安装
在 macOS 上可以使用 brew 进行安装
~ brew install grpcurl
~ grpcurl -version
grpcurl 1.9.3
使用
列出服务端的服务列表
~ grpcurl -plaintext localhost:9080 list
helloworld.Greeter
envoy.service.auth.v3.Authorization
grpc.reflection.v1.ServerReflection
grpc.reflection.v1alpha.ServerReflection
提示
这些命令假设服务端开启了反射服务,如果没有开启反射服务,则需要通过 -proto 或则 -protoset 参数指定 proto 文件或则 protoset 文件
在 go 语言中开启反射服务
import (
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
)
func main() {
server := grpc.NewServer()
reflection.Register(server)
}
查看某个服务的方法列表
~ grpcurl -plaintext localhost:9080 list envoy.service.auth.v3.Authorization
envoy.service.auth.v3.Authorization.Check
~ grpcurl -plaintext 127.0.0.1:8080 list helloworld.Greeter
helloworld.Greeter.SayHello
也可以直接加载 proto 文件的方式查看所支持的服务
~ grpcurl -import-path echo -proto echo.proto list
grpc.examples.echo.Echo
查看方法定义
~ grpcurl -plaintext 127.0.0.1:8080 describe helloworld.Greeter.SayHello
helloworld.Greeter.SayHello is a method:
rpc SayHello ( .helloworld.HelloRequest ) returns ( .helloworld.HelloReply );
查看请求参数
~ grpcurl -plaintext 127.0.0.1:8080 describe helloworld.HelloRequest
helloworld.HelloRequest is a message:
message HelloRequest {
string name = 1;
}
发送请求
~ grpcurl -d '{"name": "abc"}' -plaintext 127.0.0.1:8080 helloworld.Greeter.SayHello
{
"message": "hello"
}