grpc作用:
在A服务器内,调用B服务器的ticket服务中的get方法,那么在A服务器里,直接调用B.ticket.get()来调用。
protobuf是一个具有高效的协议数据交换格式工具库,比json等更高的转化效率。
pip install grpcio grpc-tools protobuf
syntax = "proto3";
package test;
service Bibili {
rpc HelloDewei(HelloDeweiReq) returns (HelloDeweiReply){}
}
message HelloDeweiReq {
string name = 1;
int32 age = 2;
}
message HelloDeweiReply {
string result =1;
}
python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. hello_bilibili.proto
service.py
#coding:utf-8
import time
import grpc
import hello_bilibili_pb2 as pb2
import hello_bilibili_pb2_grpc as pb2_grpc
from concurrent import futures
class Bibili(pb2_grpc.BibiliServicer):
def HelloDewei(self, request, context):
name = request.name
age = request.age
result = f'my name is {name}, iam {age} years old'
return pb2.HelloDeweiReply(result=result)
def run():
grpc_server = grpc.server(
futures.ThreadPoolExecutor(max_workers=4)
)
pb2_grpc.add_BibiliServicer_to_server(Bibili(),grpc_server)
grpc_server.add_insecure_port('0.0.0.0:5000')
print("server will start at 0.0.0.0:5000")
grpc_server.start()
try:
while 1:
time.sleep(3600)
except KeyboardInterrupt:
grpc_server.stop(0)
if __name__ == '__main__':
run()
#client.py
#coding:utf-8
import grpc
import hello_bilibili_pb2 as pb2
import hello_bilibili_pb2_grpc as pb2_grpc
def run():
conn = grpc.insecure_channel("127.0.0.1:5000")
client = pb2_grpc.BibiliStub(channel=conn)
response = client.HelloDewei(pb2.HelloDeweiReq(
name='dewei',
age = 28
))
print(response.result)
if __name__ == '__main__':
run()