redis 订阅&发布(转载)

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)订阅频道 2)监听频道中的消息
        pub = self.__conn.pubsub()
        # 订阅频道,与publish()中指定的频道一样。消息会发布到这个频道中
        pub.subscribe(self.chan_sub)
        ret = pub.parse_response()  # [b'subscribe', b'fm86', 1]
        print("ret:%s" % ret)
        return pub
复制代码

redis_pub.py: 发布者

from redis_helper import RedisHelper
                
                
obj = RedisHelper()
for i in range(5):
    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)订阅频道 2)监听频道中的消息
        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(5):
    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-8 -*-
import redis
 
pool = redis.ConnectionPool(host='192.168.0.110', port=6379)
r = redis.Redis(connection_pool=pool)
r.set('name', 'zhangsan')   #添加
print (r.get('name'))   #获取

 

posted on   我和你并没有不同  阅读(233)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示