pip install grpcio grpcio_tools protobuf
1.定义protobuf文件
// 语法
syntax = "proto3";
// 包名
package test;
// service定义
service SayHello {
// 定义方法、请求、响应message
rpc HelloDonghao (HelloDonghaoReq) returns (HelloDonghaoResPonse) {}
}
message HelloDonghaoReq {
string name = 1;
int32 age = 2;
}
message HelloDonghaoResPonse {
string result = 1;
}
2.生成文件:python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. hello_word.proto
3.编写service
# -*- coding: utf-8 -*-
"""
Author : donghao
Time : 2021/6/27 11:32 上午
"""
from __future__ import absolute_import
import grpc
import hello_word_pb2 as pb2
import hello_word_pb2_grpc as pb2_grpc
# 创建线程数量
from concurrent import futures
class SayHello(pb2_grpc.SayHelloServicer):
def HelloDonghao(self, request, context):
name = request.name
age = request.age
print(name, age)
result = f'my name is {name}, age is {age}'
return pb2.HelloDonghaoResPonse(result=result)
def run():
grpc_server = grpc.server(
futures.ThreadPoolExecutor(max_workers=2)
)
pb2_grpc.add_SayHelloServicer_to_server(SayHello(), grpc_server)
grpc_server.add_insecure_port('0.0.0.0:5000')
grpc_server.start()
print('grpc start at: 0.0.0.0:5000')
grpc_server.wait_for_termination()
if __name__ == '__main__':
run()
4.编写client端代码
# -*- coding: utf-8 -*-
"""
Author : donghao
Time : 2021/6/27 11:39 上午
"""
from __future__ import absolute_import
import grpc
import hello_word_pb2 as pb2
import hello_word_pb2_grpc as grpc_pb2
def run():
# 定义频道
conn = grpc.insecure_channel('0.0.0.0:5000')
client = grpc_pb2.SayHelloStub(channel=conn)
resp = client.HelloDonghao(pb2.HelloDonghaoReq(
name='donghao', age=23
))
print(resp.result)
if __name__ == '__main__':
run()
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)