// 文件名 hello.proto
syntax = "proto3";//使用第三版协议编译
service Greeter { // 服务端定义
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
message HelloRequest { // 请求消息,既参数
string name = 1; //占位符,既说明是第几个参数,如果还有,则标识符为2
}
message HelloReply { // 返回消息,既返回,return
string message = 1;
}
参考: gRPC之proto语法
python -m grpc_tools.protoc -I./ --python_out=. --grpc_python_out=. ./hello.proto
greeter_server.py
from concurrent import futures
import time
import grpc
import hello_pb2
import hello_pb2_grpc
class Greeter(hello_pb2_grpc.GreeterServicer): # 继承grpc的类
def SayHello(self, request, context): # 重写方法
return hello_pb2.HelloReply(message='Hello, %s!' % request.name)
def serve():# gRPC 服务器
# 创建多线程服务
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
# 将Greeter类添加到server
hello_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
# 绑定端口
server.add_insecure_port('[::]:50051')
server.start() # 不会阻塞,所以要循环等待
try:
while True:
time.sleep(60 * 60 * 24)
except KeyboardInterrupt:
server.stop(0)
if __name__ == '__main__':
serve()
greeter_client.py
import grpc
import hello_pb2
import hello_pb2_grpc
def run():
channel = grpc.insecure_channel('localhost:50051')
stub = hello_pb2_grpc.GreeterStub(channel)
response = stub.SayHello(hello_pb2.HelloRequest(name='wang'))
print("Greeter client received: " + response.message)
if __name__ == '__main__':
run()
参考:
Python gRPC 入门