使用 grpcurl 通过命令行访问 gRPC 服务

陈孙
• 阅读 5896

原文链接: 使用 grpcurl 通过命令行访问 gRPC 服务

一般情况下测试 gRPC 服务,都是通过客户端来直接请求服务端。如果客户端还没准备好的话,也可以使用 BloomRPC 这样的 GUI 客户端。

如果环境不支持安装这种 GUI 客户端的话,那么有没有一种工具,类似于 curl 这样的,直接通过终端,在命令行发起请求呢?

答案肯定是有的,就是本文要介绍的 grpcurl

gRPC Server

首先来写一个简单的 gRPC Server:

helloworld.proto:

syntax = "proto3";

package proto;

// The greeting service definition.
service Greeter {
    // Sends a greeting
    rpc SayHello (HelloRequest) returns (HelloReply) {}
}

// The request message containing the user's name.
message HelloRequest {
    string name = 1;
}

// The response message containing the greetings
message HelloReply {
    string message = 1;
}

main.go

package main

import (
    "context"
    "fmt"
    "grpc-hello/proto"
    "log"
    "net"

    "google.golang.org/grpc"
    "google.golang.org/grpc/reflection"
)

func main() {
    lis, err := net.Listen("tcp", ":50051")
    if err != nil {
        log.Fatalf("failed to listen: %v", err)
    }

    server := grpc.NewServer()
    // 注册 grpcurl 所需的 reflection 服务
    reflection.Register(server)
    // 注册业务服务
    proto.RegisterGreeterServer(server, &greeter{})

    fmt.Println("grpc server start ...")
    if err := server.Serve(lis); err != nil {
        log.Fatalf("failed to serve: %v", err)
    }
}

type greeter struct {
}

func (*greeter) SayHello(ctx context.Context, req *proto.HelloRequest) (*proto.HelloReply, error) {
    fmt.Println(req)
    reply := &proto.HelloReply{Message: "hello"}
    return reply, nil
}

运行服务:

go run main.go

server start ...

grpcurl 安装

这里我介绍三种方式:

Mac

brew install grpcurl

Docker

# Download image
docker pull fullstorydev/grpcurl:latest
# Run the tool
docker run fullstorydev/grpcurl api.grpc.me:443 list

go tool

如果有 Go 环境的话,可以通过 go tool 来安装:

go install github.com/fullstorydev/grpcurl/cmd/grpcurl@latest

grpcurl 使用

在使用 grpcurl 时,需要通过 -cert-key 参数设置公钥和私钥文件,表示链接启用了 TLS 协议的服务。

对于没有启用 TLS 协议的 gRPC 服务,通过 -plaintext 参数忽略 TLS 证书的验证过程。

如果是 Unix Socket 协议,则需要指定 -unix 参数。

查看服务列表:

grpcurl -plaintext 127.0.0.1:50051 list

输出:

grpc.reflection.v1alpha.ServerReflection
proto.Greeter

查看某个服务的方法列表:

grpcurl -plaintext 127.0.0.1:50051 list proto.Greeter

输出:

proto.Greeter.SayHello

查看方法定义:

grpcurl -plaintext 127.0.0.1:50051 describe proto.Greeter.SayHello

输出:

proto.Greeter.SayHello is a method:
rpc SayHello ( .proto.HelloRequest ) returns ( .proto.HelloReply );

查看请求参数:

grpcurl -plaintext 127.0.0.1:50051 describe proto.HelloRequest

输出:

proto.HelloRequest is a message:
message HelloRequest {
  string name = 1;
}

请求服务:

grpcurl -d '{"name": "zhangsan"}' -plaintext 127.0.0.1:50051 proto.Greeter.SayHello

输出:

{
  "message": "hello"
}

-d 参数后面也可以跟 @,表示从标准输入读取 json 参数,一般用于输入比较复杂的 json 数据,也可以用于测试流方法。

grpcurl -d @ -plaintext 127.0.0.1:50051 proto.Greeter.SayHello

可能遇到的错误

可能会遇到三个报错:

1、gRPC Server 未启用 TLS:

报错信息:

Failed to dial target host "127.0.0.1:50051": tls: first record does not look like a TLS handshake

解决:

请求时增加参数:-plaintext,参考上面的命令。

2、服务没有启动 reflection 反射服务

报错信息:

Failed to list services: server does not support the reflection API

解决:

这行代码是关键,一定要包含:

// 注册 grpcurl 所需的 reflection 服务
reflection.Register(server)

3、参数格式错误:

报错信息:

Error invoking method "greet.Greeter/SayHello": error getting request data: invalid character 'n' looking for beginning of object key string

解决:

-d 后面参数为 json 格式,并且需要使用 '' 包裹起来。

总结:

用这个工具做一些简单的测试还是相当方便的,上手也简单。只要掌握文中提到的几条命令,基本可以涵盖大部分的测试需求了。


扩展阅读:

  1. https://appimage.github.io/BloomRPC/
  2. https://github.com/fullstorydev/grpcurl

文章中的脑图和源码都上传到了 GitHub,有需要的同学可自行下载。

地址: https://github.com/yongxinz/gopher/tree/main/blog

往期文章列表:

  1. 被 Docker 日志坑惨了
  2. 推荐三个实用的 Go 开发工具
  3. 这个 TCP 问题你得懂:Cannot assign requested address

Go 专栏文章列表:

  1. Go 专栏|开发环境搭建以及开发工具 VS Code 配置
  2. Go 专栏|变量和常量的声明与赋值
  3. Go 专栏|基础数据类型:整数、浮点数、复数、布尔值和字符串
  4. Go 专栏|复合数据类型:数组和切片 slice
  5. Go 专栏|复合数据类型:字典 map 和 结构体 struct
  6. Go 专栏|流程控制,一网打尽
  7. Go 专栏|函数那些事
  8. Go 专栏|错误处理:defer,panic 和 recover
  9. Go 专栏|说说方法
  10. Go 专栏|接口 interface
  11. Go 专栏|并发编程:goroutine,channel 和 sync
点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
4年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
菜园前端 菜园前端
2年前
DOM 文档对象模型使用教程来喽!
原文链接:HTML模板html我是网站标题访问节点通过id访问指定节点getElementByIdjavascriptvarnodedocument.getElementById('box')通过name访问指定节点getElementsByNamejav
peter peter
4年前
Go-GRPC 初体验
grpc跟常见的clientserver模型相似(dubbo)grpc编码之前需要准备以下环境:安装protobuf,grpc的client与server之间消息传递使用的protoc格式消息,比起json,xml速度快安装grpc的源码包下面开始编写grpc示例代码:1.首先编写proto文件,示例:helloworld
Wesley13 Wesley13
3年前
gRPC官方文档(gRPC基础:C++)
文章来自gRPC官方文档中文版(http://doc.oschina.net/grpc?t56831)本教程提供了C程序员如何使用gRPC的指南。通过学习教程中例子,你可以学会如何:在一个.proto文件内定义服务.用protocolbuffer编译器生成服务器和客户端代码.使用gRPC的C
Stella981 Stella981
3年前
SpringBoot整合Redis乱码原因及解决方案
问题描述:springboot使用springdataredis存储数据时乱码rediskey/value出现\\xAC\\xED\\x00\\x05t\\x00\\x05问题分析:查看RedisTemplate类!(https://oscimg.oschina.net/oscnet/0a85565fa
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Easter79 Easter79
3年前
SpringBoot整合Redis乱码原因及解决方案
问题描述:springboot使用springdataredis存储数据时乱码rediskey/value出现\\xAC\\xED\\x00\\x05t\\x00\\x05问题分析:查看RedisTemplate类!(https://oscimg.oschina.net/oscnet/0a85565fa
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
1年前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这
美凌格栋栋酱 美凌格栋栋酱
5个月前
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(