使用Python的gRPC读取Redis数据(读取)
需要三个东西:配置文件、服务器程序和客户端程序。
设置文件 (shè
syntax = "proto3";
package redis_read;
service Greeter {
rpc RedisRead (RedisRequest) returns (RedisReply) {}
}
message RedisRequest {
string key = 1;
}
message RedisReply {
string str_json = 1;
}
服务器程序
#! /usr/bin/python
#
# redis_read_server.py
#
# Feb/08/2020
# --------------------------------------------------------------
import sys
import redis
from concurrent import futures
import logging
import grpc
import redis_read_pb2
import redis_read_pb2_grpc
# --------------------------------------------------------------
def read_redis_proc(key_in):
rr = redis.Redis(host='localhost', port=6379, db=0)
#
str_json = rr.get(key_in).decode ()
#
return str_json
# --------------------------------------------------------------
class Greeter(redis_read_pb2_grpc.GreeterServicer):
def RedisRead(self, request, context):
sys.stderr.write("*** RedisRead ***\n")
sys.stderr.write("*** key = %s ***\n" % request.key)
str_out_aa = read_redis_proc(request.key)
sys.stderr.write(str_out_aa + "\n")
return redis_read_pb2.RedisReply(str_json=str_out_aa)
# --------------------------------------------------------------
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
redis_read_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
server.add_insecure_port('[::]:50051')
server.start()
server.wait_for_termination()
# --------------------------------------------------------------
if __name__ == '__main__':
logging.basicConfig()
serve()
# --------------------------------------------------------------
客户端程序
#! /usr/bin/python
#
# redis_read_client.py
#
# Feb/08/2020
#
# --------------------------------------------------------------
from __future__ import print_function
import logging
import json
import grpc
import sys
import redis_read_pb2
import redis_read_pb2_grpc
# --------------------------------------------------------------
def display_proc(str_json):
unit_aa = json.loads(str_json)
str_out = unit_aa['name']
str_out += "\t"+ str(unit_aa['population'])
str_out += "\t"+ unit_aa['date_mod']
print(str_out)
#
# --------------------------------------------------------------
def run():
key_in = sys.argv[1]
with grpc.insecure_channel('localhost:50051') as channel:
stub = redis_read_pb2_grpc.GreeterStub(channel)
response = stub.RedisRead(redis_read_pb2.RedisRequest(key=key_in))
# print("Greeter client received aa: " + response.str_json)
display_proc(response.str_json)
#
# --------------------------------------------------------------
if __name__ == '__main__':
logging.basicConfig()
run()
# --------------------------------------------------------------
创建 gRPC 的代码。
python -m grpc_tools.protoc -I. \
--python_out=. \
--grpc_python_out=. \
./redis_read.proto
启动服务器程序
./redis_read_server.py
执行客户端程序
$ ./redis_read_client.py t1854
大野 89612 2003-9-9