当前位置: 首页 > 科技观察

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

时间:2023-03-17 18:35:34 科技观察

一般测试gRPC服务,客户端直接向服务端发起请求。如果客户端还没有准备好,也可以使用像BloomRPC这样的GUI客户端。如果环境不支持安装这个GUI客户端,那么有没有类似curl的工具,直接使用终端在命令行发起请求呢?答案肯定是肯定的,就是本文要介绍的grpcurl。gRPCServer首先写一个简单的gRPCServer:syntax="proto3";packageproto;//greetingservicedefinition.serviceGreeter{//SendsgreetingrpcSayHello(HelloRequest)returns(HelloReply){}}//Therequestmessagecontainingtheuser'sname.messageHelloRequest{stringname=1;}//TheresponsemessagecontainingthegreetingsmessageHelloReply{stringmessage=1;}main.gopackagemainimport("context""fmt""grpc-hello/proto""log""net""google.golang.org/grpc""google.golang.org/grpc/reflection")funcmain(){lis,err:=net.Listen("tcp",":50051")iferr!=nil{log.Fatalf("failedtolisten:%v",err)}server:=grpc.NewServer()//注册grpcurl需要的反射服务reflection.Register(server)//注册业务服务proto.RegisterGreeterServer(server,&greeter{})fmt.Println("grpcserverstart...")iferr:=server.Serve(lis);err!=nil{log.Fatalf("failedtoserve:%v",err)}}typegreeterstruct{}func(*greeter)SayHello(ctxcontext.Context,req*proto.HelloRequest)(*proto.HelloReply,error){fmt.Println(req)reply:=&proto.HelloReply{Message:"hello"}returnreply,nil}运行服务:gorunmain.goserverstart...grpcurl安装这里我介绍三种方式:MacbrewinstallgrpcurlDocker#Downloadimagedockerpullfullstorydev/grpcurl:latest#Runthetooldockerrunfullstorydev/grpcurlapi.grpc.me:443listgo工具如果你有Go环境,可以通过go工具安装:goinstallgithub.com/fullstorydev/grpcurl/cmd/grpcurl@latestgrpcurl使用查看服务列表:grpcurl-plaintext127.0.0.1:50051list输出:grpc.reflection.v1alpha.ServerReflectionproto.Greeter查看某个服务的方法列表:grpcurl-plaintext127.0.0.1:50051listproto.Greeter输出:proto.Greeter.SayHello查看方法定义:grpcurl-plaintext127.0.0.1:50051describeproto.Greeter.SayHello输出:proto.Greeter.SayHelloisamethod:rpcSayHello(.proto.HelloRequest)returns(.proto.HelloReply);查看请求参数:grpcurl-plaintext127.0.0.1:50051describeproto.HelloRequest输出:proto.HelloRequestisamessage:messageHelloRequest{stringname=1;}请求服务:grpcurl-d'{"name":";zhangsan"}'-plaintext127.0.0.1:50051proto.Greeter.SayHelloOutput:{"message":"hello"}可能会遇到两个错误:1.gRPCServerisnotenabledTLS:errorInformation:Failedtodialtargethost"127.0.0.1:50051":tls:firstrecorddoesnotlooklikeaTLShandshake解决方法:请求时添加参数:-plaintext,参考上述命令2.参数格式错误:错误信息:Errorinvokingmethod"greet.Greeter/SayHello":er??rorgettingrequestdata:invalidcharacter'n'lookingforbeginningofobjectkeystring解决方法:-d后面的参数是json格式,需要用''包裹。总结:用这个工具做一些简单的测试还是挺方便的,而且上手也很容易,只要掌握几个命令文中提到,基本可以覆盖大部分测试需求。扩展阅读:https://appimage.github.io/BloomRPC/https://github.com/fullstorydev/grpcurl文中的脑图和源码已上传至GitHub,如有必要y同学们可以自行下载。地址:https://github.com/yongxinz/gopher/tree/main/blog本文转载自微信公众号「AlwaysBeta」,可通过以下二维码关注。转载本文请联系AlwaysBeta公众号。