百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术教程 > 正文

Python Redis订阅发布功能详解(python3 redis)

mhr18 2024-10-29 14:34 17 浏览 0 评论

我们也可以用订阅的方法来得到某个键的值,而且仅在该值发生变化时才会被触发。其基本工作模式是:首先订阅某个频道的消息,如果该频道有消息发送过来,那么相应的处理函数就会被执行。

基本用法

实现订阅发布功能需要两个角色,一个是发布者,也就是消息发布者;另外一个是订阅者,就是消息接收和处理者。所以一般需要分别用代码实现这两个角色。

订阅者代码如下:

import redis                                    # 引入库
r = redis.Redis(host='10.20.17.13',port=6379)    # 建立连接
channel = 'test_channel1'                        # 定义频道名
sub_obj = r.pubsub()                            # 创建订阅对象
sub_obj.subscribe(channel)                        # 订阅到指定的频道上
sub_obj.parse_response()                        # 等待消息
while True:                                        # 无限循环
    msg = sub_obj.parse_response()                # 得到消息内容
    print(msg) 

运行后收到的消息是一个列表,显示如下:

[b'message', b'test_channel1', b'msg1']
[b'message', b'test_channel1', b'msg2']


发布者代码如下:

import redis
r = redis.Redis(host='10.20.17.13',port=6379)    # 建立连接
channel = 'test_channel1'                        # 频道名,要和订阅代码一致
r.publish(channel, "msg1")                        # 发送消息
r.publish(channel, "msg2")

我们可以像前面演示的那样编写两个程序,分别完成发布和订阅功能,也可以用多线程的方式,将它们写到一份代码里,但是这两个功能需要在两个线程中完成。

下面是合并后的代码,实现了和前面代码一样的功能,但是更有利于演示功能:

#encoding: utf-8
import redis
import time, _thread
def thread_entry(sub_obj):
    for i in range(2):
        msg = sub_obj.parse_response()
        print("Received Msg: %s" % msg)
r = redis.Redis(host='127.0.0.1',port=6379)
channel = 'test_channel1'
sub_obj = r.pubsub()
sub_obj.subscribe(channel)
sub_obj.parse_response()
_thread.start_new_thread(thread_entry, (sub_obj,))        # 启动订阅线程
time.sleep(1)
r.publish(channel, "msg1")
time.sleep(1)
r.publish(channel, "msg2")
time.sleep(1)

运行后的结果如下:

$ python pubsubThreads1.py
·Received Msg: [b'message', b'test_channel1', b'msg1']
Received Msg: [b'message', b'test_channel1', b'msg2']

前面这种方式看起来和消息队列没有太大的区别,就是一个任务负责发布消息,另外一个任务负责接收和处理消息。

但是它们还是有区别的,具体如下:
1) 消息队列中的消息一般只能被一个任务处理,而订阅方式可以有很多个接收消息的任务,它们都会接收到相同的消息,都能进行相关的处理。我们可以修改前面的多线程代码,启动多个订阅线程,然后发送一个消息,看看有多少个消息被接收并被处理。

下面是修改后的代码:

import redis
import time, _thread
def thread_entry(r, channel, sub_id):            # 订阅线程
    sub_obj = r.pubsub()                        # 创建对象
    sub_obj.subscribe(channel)                    # 订阅指定频道的消息
    sub_obj.parse_response()                    # 丢掉第一个消息
    for i in range(10):                            # 处理接收到的其他消息
        msg = sub_obj.parse_response()
        print("Thread [%d] Received Msg: %s" % (sub_id, msg))
r = redis.Redis(host='127.0.0.1',port=6379)    # 建立连接
channel = 'test_channel1'
time.sleep(1)
# 启动三个订阅线程,其id分别是1、2和3
_thread.start_new_thread(thread_entry, (r, channel, 1))
_thread.start_new_thread(thread_entry, (r, channel, 2))
_thread.start_new_thread(thread_entry, (r, channel, 3))
time.sleep(2)
r.publish(channel, "msg1")                        # 发布第一个消息
time.sleep(2)
r.publish(channel, "msg2")                        # 发布第二个消息
time.sleep(2)

运行后的结果如下:

$ python multiSub1.py
Thread [1] Received Msg: [b'message', b'test_channel1', b'msg1']
Thread [3] Received Msg: [b'message', b'test_channel1', b'msg1']
Thread [2] Received Msg: [b'message', b'test_channel1', b'msg1']
Thread [1] Received Msg: [b'message', b'test_channel1', b'msg2']
Thread [2] Received Msg: [b'message', b'test_channel1', b'msg2']
Thread [3] Received Msg: [b'message', b'test_channel1', b'msg2']

可以看到每个消息都被三个线程分别接收和处理了,不会像消息队列那样,仅一个线程能够得到这个消息。

2) 消息队列中的消息一般一直在队列中,直到被处理任务读出。而订阅方式可以没有订阅者,这时发布的消息就没有任务进行处理,但是该消息不会一直保存在队列中,其会自动消失。

import redis
import time, _thread
def thread_entry(sub_obj):                        # 订阅线程
    while True:                                    # 一直接收消息
        msg = sub_obj.parse_response()            # 得到消息
        print("Received Msg: %s" % msg)    # 打印消息
r = redis.Redis(host='127.0.0.1',port=6379)    # 建立连接
channel = 'test_channel1'        # 定义频道
sub_obj = r.pubsub()            # 创建订阅对象,但是还没有和频道关联起来
# 现在没有接收者,发送的消息会丢失
r.publish(channel, "msg1")
sub_obj.subscribe(channel)        # 建立和频道的联系,以后该频道的消息不回丢了
sub_obj.parse_response()        # 丢掉第一个消息,这个是订阅成功的消息
time.sleep(1)
# 启动订阅线程
_thread.start_new_thread(thread_entry, (sub_obj,))
time.sleep(1)
r.publish(channel, "msg2")        # 发送第二个消息
time.sleep(1)
r.publish(channel, "msg3")        # 发送第三个消息
time.sleep(1)

运行后的结果如下:

$ python lostMsg.py
Received Msg: [b'message', b'test_channel1', b'msg2']
Received Msg: [b'message', b'test_channel1', b'msg3']

可以看到第一个消息 msg1 是没有被接收到的,原因就是在发送 msg1 时,没有人订阅该频道。

订阅多个频道

subscribe() 函数可以带有多个参数,表示其同时订阅多个频道。

下面演示了同时订阅两个频道的用法:

import redis                                    # 引入redis模块
import time, _thread                            # 引入时间和线程模块
def thread_entry(sub_obj):                        # 线程入口函数
    for i in range(10):                            # 循环10次
        msg = sub_obj.parse_response()            # 得到消息
        print("Received Msg: %s" % msg)            # 打印消息内容
r = redis.Redis(host='127.0.0.1',port=6379)    # 连接Redis服务器
channel1 = 'test_channel1'                        # 两个频道
channel2 = 'test_channel2'
sub_obj = r.pubsub()
sub_obj.subscribe(channel1, channel2)
sub_obj.parse_response()
sub_obj.parse_response()
_thread.start_new_thread(thread_entry, (sub_obj,))    # 启动线程
time.sleep(1)
r.publish(channel1, "msg1")                        # 在第一个频道发送消息
time.sleep(1)
r.publish(channel2, "msg2")                        # 在第二个频道发送消息
time.sleep(1)

运行后的结果如下:

$ python pubmultisubThreads1.py
Received Msg: [b'message', b'test_channel1', b'msg1']
Received Msg: [b'message', b'test_channel2', b'msg2']


频道使用通配符

如果使用 psubscribe() 来订阅某个频道,可以是使用通配符“*”,表示符合该模式的所有频道。例如可以用“test_channel*”来表示所有以 test_channel 开头的频道,这样发送给 test_channel1、test_channel2 等频道的消息它都可以收到。

下面是这种用法的一个演示:

import redis
import time, _thread
def thread_entry(r, channel, id):
    sub_obj = r.pubsub()
    group_channel = channel + "*"
    sub_obj.psubscribe(group_channel)
    sub_obj.parse_response()
    for i in range(10):
        msg = sub_obj.parse_response()
        print("Thread %d Received Msg: %s" % (id, msg))
r = redis.Redis(host='127.0.0.1',port=6379)
channel = 'test_channel'
# 启动订阅线程
_thread.start_new_thread(thread_entry, (r, channel, 1))
_thread.start_new_thread(thread_entry, (r, channel, 2))
_thread.start_new_thread(thread_entry, (r, channel, 3))
_thread.start_new_thread(thread_entry, (r, channel, 4))
time.sleep(1)
r.publish("test_channel1", "msg1")
time.sleep(1)
r.publish("test_channel2", "msg2")
time.sleep(1)
r.publish("test_channel3", "msg3")
time.sleep(1)

运行后的输出如下:

$ python groupsend.py
Thread 3 Received Msg: [b'pmessage', b'test_channel*', b'test_
channel1', b'msg1']
Thread 1 Received Msg: [b'pmessage', b'test_channel*', b'test_
channel1', b'msg1']
Thread 4 Received Msg: [b'pmessage', b'test_channel*', b'test_
channel1', b'msg1']
Thread 2 Received Msg: [b'pmessage', b'test_channel*', b'test_
channel1', b'msg1']
Thread 4 Received Msg: [b'pmessage', b'test_channel*', b'test_
channel2', b'msg2']
Thread 2 Received Msg: [b'pmessage', b'test_channel*', b'test_
channel2', b'msg2']
Thread 1 Received Msg: [b'pmessage', b'test_channel*', b'test_
channel2', b'msg2']
Thread 3 Received Msg: [b'pmessage', b'test_channel*', b'test_
channel2', b'msg2']
Thread 4 Received Msg: [b'pmessage', b'test_channel*', b'test_
channel3', b'msg3']
Thread 2 Received Msg: [b'pmessage', b'test_channel*', b'test_
channel3', b'msg3']
Thread 3 Received Msg: [b'pmessage', b'test_channel*', b'test_
channel3', b'msg3']
Thread 1 Received Msg: [b'pmessage', b'test_channel*', b'test_
channel3', b'msg3']

相关推荐

Redis合集-使用benchmark性能测试

采用开源Redis的redis-benchmark工具进行压测,它是Redis官方的性能测试工具,可以有效地测试Redis服务的性能。本次测试使用Redis官方最新的代码进行编译,详情请参见Redis...

Java简历总被已读不回?面试挂到怀疑人生?这几点你可能真没做好

最近看了几十份简历,发现大部分人不是技术差,而是不会“卖自己”——一、简历死穴:你写的不是经验,是岗位说明书!反面教材:ד使用SpringBoot开发项目”ד负责用户模块功能实现”救命写法:...

redission YYDS(redission官网)

每天分享一个架构知识Redission是一个基于Redis的分布式Java锁框架,它提供了各种锁实现,包括可重入锁、公平锁、读写锁等。使用Redission可以方便地实现分布式锁。red...

从数据库行锁到分布式事务:电商库存防超卖的九重劫难与破局之道

2023年6月18日我们维护的电商平台在零点刚过3秒就遭遇了严重事故。监控大屏显示某爆款手机SKU_IPHONE13_PRO_MAX在库存仅剩500台时,订单系统却产生了1200笔有效订单。事故复盘发...

SpringBoot系列——实战11:接口幂等性的形而上思...

欢迎关注、点赞、收藏。幂等性不仅是一种技术需求,更是数字文明对确定性追求的体现。在充满不确定性的网络世界中,它为我们建立起可依赖的存在秩序,这或许正是技术哲学最深刻的价值所在。幂等性的本质困境在支付系...

如何优化系统架构设计缓解流量压力提升并发性能?Java实战分享

如何优化系统架构设计缓解流量压力提升并发性能?Java实战分享在高流量场景下。首先,我需要回忆一下常见的优化策略,比如负载均衡、缓存、数据库优化、微服务拆分这些。不过,可能还需要考虑用户的具体情况,比...

Java面试题: 项目开发中的有哪些成长?该如何回答

在Java面试中,当被问到“项目中的成长点”时,面试官不仅想了解你的技术能力,更希望看到你的问题解决能力、学习迭代意识以及对项目的深度思考。以下是回答的策略和示例,帮助你清晰、有说服力地展示成长点:一...

互联网大厂后端必看!Spring Boot 如何实现高并发抢券逻辑?

你有没有遇到过这样的情况?在电商大促时,系统上线了抢券活动,结果活动刚一开始,服务器就不堪重负,出现超卖、系统崩溃等问题。又或者用户疯狂点击抢券按钮,最后却被告知无券可抢,体验极差。作为互联网大厂的后...

每日一题 |10W QPS高并发限流方案设计(含真实代码)

面试场景还原面试官:“如果系统要承载10WQPS的高并发流量,你会如何设计限流方案?”你:“(稳住,我要从限流算法到分布式架构全盘分析)…”一、为什么需要限流?核心矛盾:系统资源(CPU/内存/数据...

Java面试题:服务雪崩如何解决?90%人栽了

服务雪崩是指微服务架构中,由于某个服务出现故障,导致故障在服务之间不断传递和扩散,最终造成整个系统崩溃的现象。以下是一些解决服务雪崩问题的常见方法:限流限制请求速率:通过限流算法(如令牌桶算法、漏桶算...

面试题官:高并发经验有吗,并发量多少,如何回复?

一、有实际高并发经验(建议结构)直接量化"在XX项目中,系统日活用户约XX万,核心接口峰值QPS达到XX,TPS处理能力为XX/秒。通过压力测试验证过XX并发线程下的稳定性。"技术方案...

瞬时流量高并发“保命指南”:这样做系统稳如泰山,老板跪求加薪

“系统崩了,用户骂了,年终奖飞了!”——这是多少程序员在瞬时大流量下的真实噩梦?双11秒杀、春运抢票、直播带货……每秒百万请求的冲击,你的代码扛得住吗?2025年了,为什么你的系统一遇高并发就“躺平”...

其实很多Java工程师不是能力不够,是没找到展示自己的正确姿势。

其实很多Java工程师不是能力不够,是没找到展示自己的正确姿势。比如上周有个小伙伴找我,五年经验但简历全是'参与系统设计''优化接口性能'这种空话。我就问他:你做的秒杀...

PHP技能评测(php等级考试)

公司出了一些自我评测的PHP题目,现将题目和答案记录于此,以方便记忆。1.魔术函数有哪些,分别在什么时候调用?__construct(),类的构造函数__destruct(),类的析构函数__cal...

你的简历在HR眼里是青铜还是王者?

你的简历在HR眼里是青铜还是王者?兄弟,简历投了100份没反应?面试总在第三轮被刷?别急着怀疑人生,你可能只是踩了这些"隐形求职雷"。帮3630+程序员改简历+面试指导和处理空窗期时间...

取消回复欢迎 发表评论: