grpc介绍
“gRPC是一个google开发的高性能、开源、通用的远程过程调用(RPC)框架,可以在任何环境中运行。它旨在通过对负载平衡、跟踪、健康检查和身份验证的可插拔支持,有效地连接数据中心内和跨数据中心的服务。gRPC基于HTTP/2协议,并使用Protocol Buffers作为其接口定义语言(IDL)。它广泛用于构建分布式系统和微服务,因为它允许在用不同编程语言编写的不同服务之间轻松通信”
1. 编写.proto文件
//使用软件版本
syntax = "proto3";
//生成两个py文件的前缀名
package algorithm;
service AlgoCaller {
//绑定请求响应方法
rpc Call (CallRequest) returns (CallReply) {}
}
//定义客户端请求字段
message CallRequest {
string funcname = 1;
int32 num =2;
}
//定义服务端响应字段
message CallReply {
string ret = 1;
}
2.使用命令行生成两个py
python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. algorithm.proto
这里有一个坑,grpc_python_out这个参数传的地址是不包含.proto文件的。.proto文件单独放到最后就行了,其他参数后面的点表示当前路径。
3.编写服务端
import grpc
from concurrent import futures
import algorithm_pb2
import algorithm_pb2_grpc
funcList=[]
def API(func):
if not func.__name__ in funcList:
funcList.append(func.__name__)
return func
#根据传递的函数名调用本地函数
@API
def erode(i):
return str(i ** 2)
class AlgoServicer(algorithm_pb2_grpc.AlgoCallerServicer):
def Call(self, request, context):
ret = eval(f"{request.funcname}({request.num})") if request.funcname in funcList else f"no api name {request.funcname}"
return algorithm_pb2.CallReply(ret=ret)
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
algorithm_pb2_grpc.add_AlgoCallerServicer_to_server(AlgoServicer(), server)
server.add_insecure_port("localhost:50051")
server.start()
print("Server started on port 50051")
server.wait_for_termination()
if __name__=="__main__":
serve()
4.编写客户端
import grpc
import algorithm_pb2
import algorithm_pb2_grpc
import time
def connect():
channel = grpc.insecure_channel("localhost:50051")
stub = algorithm_pb2_grpc.AlgoCallerStub(channel)
i = 0
while True:
response = stub.Call(algorithm_pb2.CallRequest(funcname="erode", num=i))
print(f"Received: {response.ret}")
time.sleep(1)
i += 1
if __name__ == '__main__':
connect()
5.测试
先运行服务端程序,再运行客户端程序即可。客户端传int消息到服务端,服务端收到int然后进行平方运算返回到客户端打印
#服务端log
add api erode
Server started on port 50051
...
#客户端log
Received: 0
Received: 1
Received: 4
Received: 9
Received: 16
Received: 25
Received: 36
....