python grpc初使用
1 .环境安装
sudo pip install grpcio
sudo pip install protobuf
sudo pip install grpcio-tools
文件目录结构如下:
├── client
│ └── client.py
├── example
│ ├── build.txt
│ ├── data.proto
│ └── __init__.py
└── server
└── server.py
2 .protobuf使用
在 example 目录下,执行:
python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. ./data.proto
此时会生成data_pb2_grpc.py 与data_pb2.py
example 下的目录如下:
├── build.txt
├── data_pb2_grpc.py
├── data_pb2.py
├── data.proto
└── __init__.py
3 . test事例
Client.py的代码如下:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import grpc
import os
import sys
current_fonder_path = os.path.split(os.path.realpath(__file__))[0]
print (current_fonder_path)
protocal_path = os.path.join(current_fonder_path,"..","example")
print (protocal_path)
sys.path.append(protocal_path)
import data_pb2, data_pb2_grpc
_HOST = 'localhost'
_PORT = '8080'
def run():
conn = grpc.insecure_channel(_HOST + ':' + _PORT) # 监听频道
print(conn)
client = data_pb2_grpc.FormatDataStub(channel=conn) # 客户端使用Stub类发送请求,参数为频道,为了绑定链接
print(client)
response = client.DoFormat(data_pb2.actionrequest(text='hello,world!')) # 返回的结果就是proto中定义的类
print("received: " + response.text + str(response.value))
if __name__ == '__main__':
run()
server.py的代码如下:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import grpc
import time
from concurrent import futures
import os
import sys
current_fonder_path = os.path.split(os.path.realpath(__file__))[0]
print (current_fonder_path)
protocal_path = os.path.join(current_fonder_path,"..","example")
print (protocal_path)
sys.path.append(protocal_path)
import data_pb2,data_pb2_grpc
_ONE_DAY_IN_SECONDS = 60 * 60 * 24
_HOST = 'localhost'
_PORT = '8080'
# 实现一个派生类,重写rpc中的接口函数.自动生成的grpc文件中比proto中的服务名称多了一个Servicer
class FormatData(data_pb2_grpc.FormatDataServicer):
# 重写接口函数.输入和输出都是proto中定义的Data类型
def DoFormat(self, request, context):
str = request.text
return data_pb2.actionresponse(text=str.upper(),value=1.0) # 返回一个类实例
def serve():
# 定义服务器并设置最大连接数,corcurrent.futures是一个并发库,类似于线程池的概念
grpcServer = grpc.server(futures.ThreadPoolExecutor(max_workers=4)) # 创建一个服务器
data_pb2_grpc.add_FormatDataServicer_to_server(FormatData(), grpcServer) # 在服务器中添加派生的接口服务(自己实现了处理函数)
grpcServer.add_insecure_port(_HOST + ':' + _PORT) # 添加监听端口
grpcServer.start() # 启动服务器
try:
while True:
time.sleep(_ONE_DAY_IN_SECONDS)
except KeyboardInterrupt:
grpcServer.stop(0) # 关闭服务器
if __name__ == '__main__':
serve()
4 .实验结果如下: