一、场景
由于我们需要访问GRPC服务的方法,便于我们进行测试,所以我们开启了grpc服务的反射机制
二、安装grpcurl
https://github.com/fullstorydev/grpcurl
https://github.com/fullstorydev/grpcurl/releases 下载对应环境的包即可
sudo dpkg -i grpcurl_1.9.1_linux_amd64.deb
ubuntu系统安装
三、服务端代码
# Copyright 2018 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The reflection-enabled version of gRPC helloworld.Greeter server.""" import time from concurrent import futures import loggingimport grpc from grpc_reflection.v1alpha import reflection from grpc_reflection.v1alpha import reflection_pb2_grpc import helloworld_pb2 import helloworld_pb2_grpcclass Greeter(helloworld_pb2_grpc.GreeterServicer):def SayHello(self, request, context):print(time.time())return helloworld_pb2.HelloReply(message="Hello, %s!" % request.name)def serve():server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)SERVICE_NAMES = (helloworld_pb2.DESCRIPTOR.services_by_name["Greeter"].full_name,reflection.SERVICE_NAME,)reflection.enable_server_reflection(SERVICE_NAMES, server)# server.add_insecure_port("[::]:50051")server.add_insecure_port("127.0.0.1:50051")server.start()server.wait_for_termination()if __name__ == "__main__":logging.basicConfig()serve()
需要安装
pip install grpcio_reflection
四、使用
1、查看服务及接口信息
$ grpcurl --plaintext localhost:50051 describe grpc.reflection.v1alpha.ServerReflection is a service: service ServerReflection {rpc ServerReflectionInfo ( stream .grpc.reflection.v1alpha.ServerReflectionRequest ) returns ( stream .grpc.reflection.v1alpha.ServerReflectionResponse ); } helloworld.Greeter is a service: service Greeter {rpc SayHello ( .helloworld.HelloRequest ) returns ( .helloworld.HelloReply );rpc SayHelloBidiStream ( stream .helloworld.HelloRequest ) returns ( stream .helloworld.HelloReply );rpc SayHelloStreamReply ( .helloworld.HelloRequest ) returns ( stream .helloworld.HelloReply ); }
2、查看服务信息
$ grpcurl --plaintext localhost:50051 list grpc.reflection.v1alpha.ServerReflection helloworld.Greeter
3、调用grpc服务方法
$ grpcurl --plaintext -d '{ "name": "World" }' localhost:50051 helloworld.Greeter/SayHello {"message": "Hello, World!" }
五、问题
1、$ grpcurl localhost:50051 describe
Failed to dial target host "localhost:50051": tls: first record does not look like a TLS handshake
由于默认是TLS加密,我们起的服务不支持,所以需要使用--plaintext参数
参考链接:
在 ASP.NET Core 中使用 gRPCurl 和 gRPCui 测试 gRPC 服务 | Microsoft Learn