工作中用到的场景是,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)

最新文章

  1. 【转载】Python 描述符简介
  2. 《静静的dojo》 总体教程介绍
  3. HTML语义化:HTML5新标签——template
  4. 演示一个使用db vault进行安全控制的示例
  5. Oracle数据库中scott用户不存在的解决方法
  6. maven 本地仓库的设置
  7. Fast特征检测
  8. 设计模式入门之装饰器模式Decorator
  9. Django 部署到Nginx
  10. 手把手教新手小白在window把自己的项目上传到github
  11. Python filter() 函数
  12. 转:RowVersion 用法
  13. echarts Y轴的刻度 跟数据对应---tooltip-formatter
  14. 基于TCP的安卓客户端开发
  15. 【AtCoder】ARC078
  16. uuid.uuid4().hex
  17. AppStore应用转让流程
  18. springBoot 打包 dubbo jar包
  19. 运用jQuery实现动态点赞
  20. ceph journal操作

热门文章

  1. 记一次GreenPlum性能调优
  2. 如何规划和选择数据库服务器:CPU、内存、磁盘、网络(转)
  3. Softmax 函数的特点和作用
  4. 深度学习(七十)darknet 实现编写mobilenet源码
  5. Jmter-Test Fragment、Include Controller和Module Controller
  6. <context:annotation-config/>,<context:component-scan/>,<mvc:annotation-driven/>区分
  7. BZOJ5297 CQOI2018 社交网络 【矩阵树定理Matrix-Tree】
  8. Adobe Acrobat 9 Pro破解方法
  9. 《DSP using MATLAB》示例Example 8.5
  10. SpringMVC传递数据的流线图