https://segmentfault.com/a/1190000016898228?utm_source=coffeephp.com

方法一:

redis_helper.py: 封装发布订阅方法

import redis

class RedisHelper(object):

    def __init__(self):
self.__conn = redis.Redis(host="localhost")
# 订阅频道
self.chan_sub = "fm104.5" def public(self, msg):
"""
在指定频道上发布消息
:param msg:
:return:
"""
# publish(): 在指定频道上发布消息,返回订阅者的数量
self.__conn.publish(self.chan_sub, msg)
return True def subscribe(self):
# 返回发布订阅对象,通过这个对象你能1)订阅频道 )监听频道中的消息
pub = self.__conn.pubsub()
# 订阅频道,与publish()中指定的频道一样。消息会发布到这个频道中
pub.subscribe(self.chan_sub)
ret = pub.parse_response() # [b'subscribe', b'fm86', ]
print("ret:%s" % ret)
return pub

redis_pub.py: 发布者

from redis_helper import RedisHelper

obj = RedisHelper()
for i in range():
obj.public("hello_%s" % i)

redis_sub.py: 订阅者

from redis_helper import RedisHelper

obj = RedisHelper()
redis_sub = obj.subscribe()
while True:
msg = redis_sub.parse_response()
print(msg)

方法二:

redis_helper.py: 封装发布订阅方法

import redis

class RedisHelper(object):

    def __init__(self):
self.__conn = redis.Redis(host="localhost")
# 频道名称
self.chan_sub = "orders" def public(self, msg):
"""
在指定频道上发布消息
:param msg:
:return:
"""
# publish(): 在指定频道上发布消息,返回订阅者的数量
self.__conn.publish(self.chan_sub, msg)
return True def subscribe(self):
# 返回发布订阅对象,通过这个对象你能1)订阅频道 )监听频道中的消息
pub = self.__conn.pubsub()
# 订阅某个频道,与publish()中指定的频道一样。消息会发布到这个频道中
pub.subscribe(self.chan_sub)
return pub

redis_pub.py:

from redis_helper import RedisHelper

obj = RedisHelper()
for i in range():
obj.public("hello_%s" % i)

redis_sub.py:

from redis_helper import RedisHelper

obj = RedisHelper()
redis_sub = obj.subscribe()
while True:
# listen()函数封装了parse_response()函数
msg = redis_sub.listen()
for i in msg:
if i["type"] == "message":
print(str(i["channel"], encoding="utf-8") + ":" + str(i["data"], encoding="utf-8"))
elif i["type"] == "subscribe":
print(str(i["channel"], encoding="utf-8"))

以上两种方式的不同之处在于,方式一使用发布订阅对象的parse_response()方法获取订阅信息,方式二使用发布订阅对象的listen()方法获取订阅信息。listen()方法是对parse_response()方法的封装,加入了阻塞,并将parse_response()返回的结果进行了处理,使结果更加简单。

==================连接池

#!/usr/bin/env python
# -*- coding:utf- -*-
import redis pool = redis.ConnectionPool(host='192.168.0.110', port=)
r = redis.Redis(connection_pool=pool)
r.set('name', 'zhangsan') #添加
print (r.get('name')) #获取

最新文章

  1. 解决FTP的URL访问不能有中文名称的问题,报java.lang.IllegalArgumentException
  2. BZOJ2599——[IOI2011]Race
  3. 第三篇 Replication:事务复制-发布服务器
  4. spring关于urlpattern
  5. PHP输出缓冲控制
  6. SCALA中类的继承
  7. opencv之人脸识别
  8. Storm入门(八)Storm实战常见问题总结(持续更新)
  9. 行为驱动:Cucumber + Selenium + Java(五) - 使用maven来实现cucumber测试和报告
  10. 另类SQL拼接方法
  11. Static需谨慎
  12. shell编程之测试和判断
  13. PyCharm+Miniconda3安装配置教程
  14. Haskell语言学习笔记(52)正则表达式
  15. MS-SQL
  16. OSG数学基础:坐标系变换
  17. 斐波那契数列,跳台阶(dp思想)
  18. 如何打卡后缀为3ds的文件
  19. Linux查看日志命令- more、less、tail、head命令的区别
  20. FreeRTOS任务暂停和启动函数

热门文章

  1. matplotlib中的imshow()
  2. Sql server 中count() 与 sum() 的区别
  3. ORA-12514错误分析
  4. (十一)El表达式详细介绍
  5. web服务器/HTTP协议基础
  6. python中列表之间求差集、交集、并集
  7. C# DataContractJsonSerializer
  8. hdu 2544 Dijstra模板题
  9. Spring Boot 默认首页
  10. 查找-------(HashCode)哈希表的原理