python redis 发布订阅 实现 RPC同步
工作中用到的场景是,python主程序发布消息到Redis,然后停住等待Redis上订阅的Response。等待过程是阻塞的,相当于把异步通信封装成同步通信,类似于Java的RPC。
RPC封装的代码如下:
import redis
import uuid
class RpcClient(object): def __init__(self, sub_channel): self.redis = redis.StrictRedis(host='localhost', port='6379') self.response = None self.channel = sub_channel self.ps = self.redis.pubsub() self.ps.subscribe(sub_channel) self.msg = self.ps.parse_response() print('开始接收----') def on_response(self, message): data = json.loads(message) if data['Result']['Uuid'] == self.uuid: self.response = data['Result'] def call(self, ch ,n): dict1 = {'Uuid': str(uuid.uuid4())} n.update(dict1) self.uuid = n['Uuid'] print('uuid is ', self.uuid) request = json.dumps(n) self.redis.publish(ch, request) while self.response is None: print('waiting...') self.on_response(self.ps.parse_response()[2]) return self.response
主程序调用方法:
# 业务逻辑... rpc = RpcClient('responseChannel') response = rpc.call('requestChannel', request_body)