gRPC-是个好东西 水深无声 2021-11-01 03:46 361阅读 0赞 最近写自动化测试脚本的时候发现,从安卓设备上用`am`执行完成,获取返回值是有问题的,没法获取到这个值,都是一堆TestRunner的信息。怎么解决喃?那就试试gRPC有没有能力来搞定~,顺便给自己充 5.2mA 的电。 # 什么是rRPC # CS模型,google 出品,逼格高! ![在这里插入图片描述][20190812010442828.png] # 使用场景 # > 在简书找到一个文章,我简单总结下,就是有安全性和性能的高要求。 需要对接口进行严格约束的情况,比如我们提供了一个公共的服务,很多人,甚至公司外部的人也可以访问这个服务,这时对于接口我们希望有更加严格的约束,我们不希望客户端给我们传递任意的数据,尤其是考虑到`安全性的因素`,我们通常需要对接口进行更加严格的约束。这时gRPC就可以通过protobuf来提供严格的接口约束。 对于`性能有更高的要求`时。有时我们的服务需要传递大量的数据,而又希望不影响我们的性能,这个时候也可以考虑gRPC服务,因为通过protobuf我们可以将数据压缩编码转化为二进制格式,通常传递的数据量要小得多,而且通过http2我们可以实现异步的请求,从而大大提高了通信效率。 但是,通常我们不会去单独使用gRPC,而是将gRPC作为一个部件进行使用,这是因为在生产环境,我们面对大并发的情况下,需要使用分布式系统来去处理,而gRPC并没有提供分布式系统相关的一些必要组件。而且,真正的线上服务还需要提供包括负载均衡,限流熔断,监控报警,服务注册和发现等等必要的组件。不过,这就不属于本篇文章讨论的主题了,我们还是先继续看下如何使用gRPC。 # showMeTheCode # 这个里面有非常全面的step-by-step的doc,包括安装啥的都有,所以非常全面了。 > [https://grpc.io/docs/quickstart/python/][https_grpc.io_docs_quickstart_python] 如果只是为了方便演示和了解下。可以直接戳链接,看代码。 这个是服务端的代码 [https://github.com/grpc/grpc/blob/master/examples/python/helloworld/greeter\_server.py][https_github.com_grpc_grpc_blob_master_examples_python_helloworld_greeter_server.py] from concurrent import futures import logging import grpc import helloworld_pb2 import helloworld_pb2_grpc class Greeter(helloworld_pb2_grpc.GreeterServicer): def SayHello(self, request, context): 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) server.add_insecure_port('[::]:50051') server.start() server.wait_for_termination() if __name__ == '__main__': logging.basicConfig() serve() 这个是客户端的代码 from __future__ import print_function import logging import grpc import helloworld_pb2 import helloworld_pb2_grpc def run(): # NOTE(gRPC Python Team): .close() is possible on a channel and should be # used in circumstances in which the with statement does not fit the needs # of the code. with grpc.insecure_channel('localhost:50051') as channel: stub = helloworld_pb2_grpc.GreeterStub(channel) response = stub.SayHello(helloworld_pb2.HelloRequest(name='you')) print("Greeter client received: " + response.message) if __name__ == '__main__': logging.basicConfig() run() [20190812010442828.png]: /images/20211101/fcdac15c09fd4590ba246a6178c083cd.png? [https_grpc.io_docs_quickstart_python]: https://grpc.io/docs/quickstart/python/ [https_github.com_grpc_grpc_blob_master_examples_python_helloworld_greeter_server.py]: https://github.com/grpc/grpc/blob/master/examples/python/helloworld/greeter_server.py
还没有评论,来说两句吧...