需要在pypi上找到对应3.5的版本
pip install grpcio-tools1.40.0 grpcio1.40.0
hello.proto
syntax = "proto3";
option cc_generic_services = true;
//定义服务接口
service GrpcService {
rpc hello (HelloRequest) returns (HelloResponse) {} //一个服务中可以定义多个接口,也就是多个函数功能
}
//请求的参数
message HelloRequest {
string data = 1; //数字1,2是参数的位置顺序,并不是对参数赋值
Skill skill = 2; //支持自定义的数据格式,非常灵活
};
//返回的对象
message HelloResponse {
string result = 1;
map<string, int32> map_result = 2; //支持map数据格式,类似dict
};
message Skill {
string name = 1;
};
3、生成python代码
PYTHONPATH=./lib/python3.5/site-packages python3 -m grpc_tools.protoc -I ./ --python_out=./ --grpc_python_out=./ ./hello.proto
- -I 指定proto所在目录
- -m 指定通过protoc生成py文件
- –python_out指定生成py文件的输出路径
- hello.proto 为输入的proto文件
生成hello_pb2_grpc.py,hello_pb2.py两个文件
grpc_server.py
#! /usr/bin/env python3
# coding=utf-8
import sys
sys.path.append('./lib/python3.5/site-packages')
import time
from concurrent import futures
import grpc
import hello_pb2_grpc, hello_pb2
_ONE_DAY_IN_SECONDS = 60 * 60 * 24
class TestService(hello_pb2_grpc.GrpcServiceServicer):
'''
实现hello方法
'''
def __init__(self):
pass
def hello(self, request, context):
'''
:param request: hello.proto -> HelloRequest
:param context:
:return: hello.proto -> HelloResponse
'''
result = request.data + " " + request.skill.name + ". I'm grpc service"
map_result = {"my_str": 123}
return hello_pb2.HelloResponse(result=str(result),
map_result=map_result)
def run():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
hello_pb2_grpc.add_GrpcServiceServicer_to_server(TestService(),server)
server.add_insecure_port('[::]:9300')
server.start()
print("start service...")
try:
while True:
time.sleep(_ONE_DAY_IN_SECONDS)
except KeyboardInterrupt:
server.stop(0)
if __name__ == '__main__':
run()
5、客户端代码
grpc_client.py
#! /usr/bin/env python3
# coding=utf-8
import sys
sys.path.append('./lib/python3.5/site-packages')
import grpc
import hello_pb2_grpc, hello_pb2
def run():
conn=grpc.insecure_channel('localhost:9300')
client = hello_pb2_grpc.GrpcServiceStub(channel=conn)
skill = hello_pb2.Skill(name="python")
request = hello_pb2.HelloRequest(data="proto", skill=skill)
response = client.hello(request)
print("client received: response.result:",response.result, "response.map_result", response.map_result)
if __name__ == '__main__':
run()
- 服务方法
- rpc OneByOne(Request) returns (Response); # 单个请求,单个响应
- rpc oneByMany(Request) returns (stream Response); # 单个请求,流式响应
- rpc ManyByOne(stream Request) returns (Response); # 流式请求,单个响应
- rpc ManyByOne(stream Request) returns (stream Response); # 流式请求,流式响应
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)