python redis 发布订阅 实现 RPC同步
2024-09-20 07:53:46
工作中用到的场景是,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='')
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)
最新文章
- 【转载】Python 描述符简介
- 《静静的dojo》 总体教程介绍
- HTML语义化:HTML5新标签——template
- 演示一个使用db vault进行安全控制的示例
- Oracle数据库中scott用户不存在的解决方法
- maven 本地仓库的设置
- Fast特征检测
- 设计模式入门之装饰器模式Decorator
- Django 部署到Nginx
- 手把手教新手小白在window把自己的项目上传到github
- Python filter() 函数
- 转:RowVersion 用法
- echarts Y轴的刻度 跟数据对应---tooltip-formatter
- 基于TCP的安卓客户端开发
- 【AtCoder】ARC078
- uuid.uuid4().hex
- AppStore应用转让流程
- springBoot 打包 dubbo jar包
- 运用jQuery实现动态点赞
- ceph journal操作
热门文章
- 记一次GreenPlum性能调优
- 如何规划和选择数据库服务器:CPU、内存、磁盘、网络(转)
- Softmax 函数的特点和作用
- 深度学习(七十)darknet 实现编写mobilenet源码
- Jmter-Test Fragment、Include Controller和Module Controller
- <;context:annotation-config/>;,<;context:component-scan/>;,<;mvc:annotation-driven/>;区分
- BZOJ5297 CQOI2018 社交网络 【矩阵树定理Matrix-Tree】
- Adobe Acrobat 9 Pro破解方法
- 《DSP using MATLAB》示例Example 8.5
- SpringMVC传递数据的流线图