GRPC简介
A high-performance, open-source universal RPC framework --官网
rpc通信
RPC(remote procedure call 远程过程调用)
是什么:提供一套应用程序之间可以通信的机制,使用C/S模型,Client进程调用Server进程提供的接口就像是调用本地函数一样。
为什么:相比较restful API的优势:
(1)gRPC都使用http底层传输协议建立C/S通信模型,但gRPC使用http2
(2)gRPC可以通过protobuf来定义由严格约束条件的接口,在提供公共API服务时,如果不希望client端给我们传递乱七八糟的数据,就可以定义输入的约束。
(3)gRPC通过protobuf将数据转化为二进制编码,减少传输数据量来提高传输性能。在需要服务器传递大量数据的场景下效率更高。
(4)gRPC通过http2.0可以方便的使用streaming模式做流式通信(通常的流式数据:视频流)
怎么用:grpc官网的一个简单Python栗子
(1)在.proto文件中定义服务。
(2)使用协议缓冲区编译器生成服务器和客户端代码。
(3)使用Python gRPC API为您的服务编写一个简单的客户端和服务器。
安装:
$ python -m pip install grpcio # 安装gprc
$ python -m pip install grpcio-tools #安装grpc-tools
Python grpc tutorial:The example code for this tutorial is in grpc/grpc/examples/python/route_guide.
QuitStart Python gRPC
下载代码
$ git clone -b v1.27.0 https://github.com/grpc/grpc
$ cd grpc/examples/python/helloworld
运行gRPC应用:用两个终端窗口一个运行Server进程,一个运行Client进程
$ python greeter_server.py # 启动Server
$ python greeter_client.py # 在另外一个terminal启动client
Server端代码
"""The Python implementation of the GRPC helloworld.Greeter server."""
from concurrent import futures
import logging
import grpc
import helloworld_pb2
import helloworld_pb2_grpc
class Greeter(helloworld_pb2_grpc.GreeterServicer):
# 自定义对外开放的API接口
def SayHello(self, request, context):
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
def serve():
# 使用ThreadPool并发处理Server任务
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
# 把对应的Greeter任务添加到rpc server中
helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
# 这里使用的非安全接口,gRPC支持TLS/SSL安全连接,以及各种鉴权机制
server.add_insecure_port('[::]:50051')
server.start()
server.wait_for_termination()
if __name__ == '__main__':
logging.basicConfig()
serve()
Client端代码
"""The Python implementation of the GRPC helloworld.Greeter client."""
from __future__ import print_function