0
0
Redisquery~5 mins

Why pub/sub enables real-time messaging in Redis

Choose your learning style9 modes available
Introduction

Pub/Sub lets messages go instantly from one place to many places without delay. This makes chatting or live updates happen in real time.

You want to send live chat messages to many users at once.
You need to update a dashboard instantly when data changes.
You want to notify many parts of your app about an event immediately.
You want to build a live feed or news ticker that updates without refreshing.
You want to send alerts or notifications to multiple users as soon as something happens.
Syntax
Redis
PUBLISH channel message
SUBSCRIBE channel

PUBLISH sends a message to a channel.

SUBSCRIBE listens to messages from a channel.

Examples
This subscribes to the 'news' channel and then sends a message to it.
Redis
SUBSCRIBE news
PUBLISH news "Hello subscribers!"
Subscribers to 'sports' get the live game start message instantly.
Redis
SUBSCRIBE sports
PUBLISH sports "Game starts now!"
Sample Program

One client listens to 'updates' channel. Another client sends a message. The subscriber gets it right away.

Redis
SUBSCRIBE updates
-- In another client:
PUBLISH updates "New update available!"
OutputSuccess
Important Notes

Pub/Sub does not save messages. If no one is listening, the message is lost.

Use Pub/Sub for live, instant messaging, not for storing data.

Summary

Pub/Sub sends messages instantly to many listeners.

It is great for live chat, notifications, and real-time updates.

Subscribers get messages only while connected.