# tools 包含代码生成工具,会自动安装依赖的 grpcio 包
pip install grpcio_tools
编写协议文件pi.proto
syntax = "proto3";
package pi;
// pi service
service PiCalculator {
// pi method
rpc Calc(PiRequest) returns (PiResponse) {}
}
// pi input
message PiRequest {
int32 n = 1;
}
// pi output
message PiResponse {
double value = 1;
}
python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. pi.proto
server端代码
# -*- coding:utf-8 -*-
# server.py
import math
import grpc
import time
from concurrent import futures
import pi_pb2, pi_pb2_grpc
# 圆周率计算服务实现类
class PiCalculatorServicer(pi_pb2_grpc.PiCalculatorServicer):
def Calc(self, request, context):
# 计算圆周率的逻辑在这里
s = 0.0
for i in range(request.n):
s += 1.0 / (2 * i + 1) / (2 * i + 1)
# 注意返回的是一个响应对象
return pi_pb2.PiResponse(value=math.sqrt(8 * s))
def main():
# 多线程服务器
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
# 实例化圆周率服务器类
pi_server = PiCalculatorServicer()
# 注册本地服务
pi_pb2_grpc.add_PiCalculatorServicer_to_server(pi_server, server)
# 监听端口
server.add_insecure_port("127.0.0.1:8080")
# 开始接收请求进行服务
server.start()
# 使用ctrl+c可以退出服务
try:
time.sleep(1000)
except KeyboardInterrupt:
server.stop(0)
if __name__ == '__main__':
main()
client端代码
# -*- coding:utf-8 -*-
# client.py
import grpc
import pi_pb2
import pi_pb2_grpc
def main():
channel = grpc.insecure_channel('localhost:8080')
# 使用 stub
client = pi_pb2_grpc.PiCalculatorStub(channel)
# 调用吧
for i in range(1, 1000):
print(client.Calc(pi_pb2.PiRequest(n=i)).value)
if __name__ == '__main__':
main()