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.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Redis Pub/Sub: Core Commands, Use Cases, and Limitations

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 CHANNELS
PUBSUB NUMSUB channel [channel...]
PUBSUB NUMPAT

3.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更加的强大
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendReal-TimeStreamsPubSubmessage-queue
MaGe Linux Operations
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.