GRPC
remote procedure call 远程过程调用,使用的时候客户端调用server端提供的接口就像是调用本地的函数一样。
Protobuf
Protobuf实际是一套类似Json或者XML的数据传输格式和规范,用于不同应用或进程之间进行通信时使用。通信时所传递的信息是通过Protobuf定义的message数据结构进行打包,然后编译成二进制的码流再进行传输或者存储
步骤:
1.通过protobuf来定义接口和数据类型
syntax = "proto3";
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
// Sends another greeting
rpc SayHelloAgain (HelloRequest) returns (HelloReply) {}
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
2.使用gRPC protobuf生成工具生成对应语言的库函数
python -m grpc_tools.protoc -I./ --python_out=. --grpc_python_out=. helloworld.proto
I: 是设定源路径
--python_out: 用于设定编译后的输出结果,其它语言请使用对应语言的option,最后一个参数是你要编译的proto文件
GRPC server端代码
from concurrent import futures
import time
import grpc
import hello_world_pb2 as helloworld_pb2
import hello_world_pb2_grpc as helloworld_pb2_grpc
_ONE_DAY_IN_SECONDS = 60 * 60 * 24
class Greeter(helloworld_pb2_grpc.GreeterServicer):
# 工作函数(方法重写)
def SayHello(self, request, context):
print(request.name)
message = "This message is from Server.And what i want to say is hello " " + request.name + " "";
return helloworld_pb2.HelloReply(message = message)
def serve():
# gRPC 服务器
server = grpc.server(futures.ThreadPoolExecutor(max_workers=4))
helloworld_pb2_grpc.add_GreeterServicer_to_server(helloworld_pb2_grpc.GreeterServicer(), server)
server.add_insecure_port('[::]:50051')
print("sever is opening ,waiting for message...")
server.start() # start() 不会阻塞,如果运行时你的代码没有其它的事情可做,需要循环等待。
try:
while True:
print('666')
time.sleep(_ONE_DAY_IN_SECONDS)
except KeyboardInterrupt:
server.stop(0)
if __name__ == '__main__':
serve()
GRPC client端代码
import hello_world_pb2_grpc, hello_world_pb2
import grpc
def run():
channel = grpc.insecure_channel('localhost:50051')
stub = hello_world_pb2_grpc.GreeterStub(channel)
response = stub.SayHello(hello_world_pb2.HelloRequest(name='donghao'))
print("Greeter client received: " + response.message)
response = stub.SayHelloAgain(hello_world_pb2.HelloRequest(name='donghao123'))
print("Greeter client received: " + response.message)
if __name__ == '__main__':
run()
output:
Greeter client received: Hello, donghao!
Greeter client received: Hello again, donghao123!