Unlock Real-Time Messaging: How Redis Pub/Sub Works and When to Use It
The article explains the publish‑subscribe (pub/sub) messaging model, its time, space, and synchronization decoupling features, typical real‑time scenarios such as chat and log processing, and details how Redis implements pub/sub through channels and pattern subscriptions, including command syntax and internal data structures.
Publish‑subscribe (pub/sub) is a messaging pattern that decouples message publishers from subscribers.
Characteristics of pub/sub
Time decoupling : Publishers and subscribers do not need to be online simultaneously.
Space decoupling : Publishers and subscribers do not need to know each other's locations.
Synchronization decoupling : Interaction is asynchronous; publishers can continuously produce messages while subscribers receive them asynchronously.
Typical use cases
Real‑time messaging systems such as instant chat or group chat.
Reducing high‑concurrency I/O write pressure, e.g., logging: producers publish log messages to a channel, and a separate logger process subscribes and writes them to files or databases asynchronously.
Redis implementation of pub/sub
(1) Channels
Subscribe to one or more channels with the SUBSCRIBE command.
Example: redis> SUBSCRIBE news.it news.sport When any subscribed channel receives a new message, the client receives it.
Redis stores channel subscription relationships in the pubsub_channels dictionary, where each key is a channel name and the value is a linked list of client connections.
When a message is published to a channel, Redis looks up the corresponding list and notifies each client.
(2) Patterns
Subscribe to channels matching a pattern with the PSUBSCRIBE command.
Example: subscribe to all channels whose names start with “news.” redis> PSUBSCRIBE news.* Pattern subscription relationships are stored in the pubsub_patterns attribute, which is a linked list where each node contains a pattern and the clients subscribed to it.
When a message is published, Redis scans this list, matches the channel name against patterns, and notifies matching subscribers.
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.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
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.
