Master Redis Pub/Sub: Core Commands, Use Cases, and Limitations
This guide explains Redis Pub/Sub as a communication pattern, shows what it can achieve, lists the most common commands with examples, demonstrates a multi‑client scenario, and outlines its drawbacks compared with newer Redis Streams.
1. What is it
是一种通信模式:发送者(PUBLISH)发送消息,订阅者(SUBSCRIBE)接收消息,可以实现进程间的消息传递
Redis可以实现消息中间件MQ的功能,通过发布订阅实现消息的引导和分流2. What can it do
Redis client can subscribe to any number of channels, similar to following multiple WeChat public accounts.
When a new message is sent via the PUBLISH command to a channel.
3. Common commands
3.1 SUBSCRIBE channel [channel...]
订阅给定的一个或多个频道的信息
推荐先执行订阅后再发布,订阅成功之前发布的消息是收不到的
订阅的客户端每次可以收到3个参数的消息
消息的种类
始发频道的名称
实际的消息内容3.2 PUBLISH channel message
发布消息到指定的频道3.3 PSUBSCRIBE pattern [pattern...]
按照模式批量订阅,订阅一个或多个符合给定模式(支持*号?号之类的)频道3.4 PUBSUB subcommand [argument [argument...]]
查看订阅与发布系统状态 PUBSUB CHANNELSPUBSUB NUMSUB channel [channel...]PUBSUB NUMPAT3.5 UNSUBSCRIBE channel [channel...]
取消订阅3.6 PUNSUBSCRIBE pattern [pattern...]
退订所有给定模式的频道4. Demo
Start three clients to demonstrate client A and B subscribing while client C publishes messages.
Demonstrate batch subscription and publishing.
Unsubscribe.
5. Summary
Redis可以实现消息中间件MQ的功能,通过发布订阅实现消息的引导和分流 Pub/Sub缺点 发布的消息在Redis系统中不能持久化,因此,必须先执行订阅,再等待消息发布,如果先发布了消息,那么该消息由于没有订阅者,消息将被直接丢弃 消息只管发送,对于发布者而言消息是即发即失的,不管接收,也没有ACK机制,无法保证消息的消费成功 以上的缺点导致Redis的Pub/Sub模式就像一个小玩具,在生产环境中几乎无用武之地,为此,Redis5.0版本新增了Stream数据结构,不但支持多播,还支持数据持久化,相比Pub/Sub更加的强大Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
