寶藏好物 gRPCurl
gRPCurl 簡介
gRPCurl[1] 是一個與 gRPC 服務器交互的命令行工具,可認爲是 gRPC 的curl
工具。
gRPCurl 用於從命令行調用 gRPC 服務器支持的 RPC 方法,gRPC 使用二進制編碼 (protobuf), 不能利用常規的 curl 工具 (早期的 curl 版本還不支持 HTTP/2)。
1. gRPCurl 工具接受 json 編碼的消息 (對人類和腳本更友好), 工具底層會轉化爲 protobuf 與服務器交互。2.gRPCurl 必須瞭解服務的 Protobuf 協議 (服務的 schema),才能調用它們, gRPCurl 通過三種方式之一實現此目的
• gRPC 服務器添加 gRPC 反射 • 直接讀取 proto 源文件 • 加載編譯後的 protoset 文件 (包含已被編碼的 proto 描述文件)
gRPCurl 特性
gRPCurl 是由 gRPC 社區創建的命令行工具,功能包括:
• 調用 gRPC 服務,包括流式服務 • 使用 gRPC 反射進行服務發現 • 列出並描述 gRPC 服務 • 支持調用安全 (TLS) 或者不安全 (plain-text) 的 gRPC 服務
ASP.NET Core 設置 grpc 反射
• 添加 Grpc.AspNetCore.Server.Reflection 包引用 •Startup.cs 註冊反射
public void ConfigureServices(IServiceCollection services)
{
services.AddGrpc();
services.AddGrpcReflection();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGrpcService<GreeterService>();
if (env.IsDevelopment())
{
endpoints.MapGrpcReflectionService();
}
});
}
服務發現、服務調用
grpcurl list/describe 可以列出 gRPC 服務端反射的 protobuf
1. grpcurl localhost:5001 list
greet.Greeter
grpc.reflection.v1alpha.ServerReflection
2. grpcurl localhost:5001 describe
greet.Greeter is a service:
service Greeter {
rpc SayHello ( .greet.HelloRequest ) returns ( .greet.HelloReply );
}
grpc.reflection.v1alpha.ServerReflection is a service:
service ServerReflection {
rpc ServerReflectionInfo ( stream .grpc.reflection.v1alpha.ServerReflectionRequest ) returns ( stream .grpc.reflection.v1alpha.ServerReflectionResponse );
}
grpc -d (Data for request contents) 傳參調用 gRPC 方法
3. grpcurl -d {"name":"World"} localhost:5001 greet.Greeter/SayHello
{
"message": "Hello World"
}
gRPCui
gRPCui[2] 是 gRPC 的交互式 Web UI, 基於 gRPCurl,並提供一個 GUI 來發現和測試 gRPC 服務,類似於 Postman 或 Swagger UI 等 HTTP 工具。
• 安裝:go install github.com/fullstorydev/grpcui/cmd/grpcui@latest• 使用:grpcui localhost:5001
會立刻打開類 Swagger 窗口:
輸入 Request Header、Request Data, 自行倒騰。
就是這麼神奇!
以上是利用 gRPC 服務反射獲取 protobuf 的方式,gRPCurl 還支持直接讀取 proto 文件。
`grpcurl -import-path ../protos -proto greet.proto -d {\"name\":\"World\"} localhost:5001 greet.Greeter/SayHello`
引用鏈接
[1]
grpcur: https://github.com/fullstorydev/grpcurl
[2]
gRPCui: https://github.com/fullstorydev/grpcui#installation
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/CSDk_vcVpry68fA3u9Crsw