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