Redis – Publish Subscribe

  • Post author:
  • Post category:Redis
  • Post comments:0 Comments

Redis Pub/Sub implements the messaging system where the senders (in redis terminology called publishers) sends the messages while the receivers (subscribers) receive them. The link by which the messages are transferred is called channel.

In Redis, a client can subscribe any number of channels.

Example

Following example explains how publish subscriber concept works. In the following example, one client subscribes a channel named ‘redisChat’.

redis 127.0.0.1:6379> SUBSCRIBE redisChat  
Reading messages... (press Ctrl-C to quit) 
1) "subscribe" 
2) "redisChat" 
3) (integer) 1 

Now, two clients are publishing the messages on the same channel named ‘redisChat’ and the above subscribed client is receiving messages.

redis 127.0.0.1:6379> PUBLISH redisChat "Redis is a great caching technique"  
(integer) 1  
redis 127.0.0.1:6379> PUBLISH redisChat "Learn redis by Adglob"  
(integer) 1   
1) "message" 
2) "redisChat" 
3) "Redis is a great caching technique" 
1) "message" 
2) "redisChat" 
3) "Learn redis by Adglob" 

Redis PubSub Commands

Following table lists some basic commands related to Redis Pub/Sub.

Sr.NoCommand & Description
1PSUBSCRIBE pattern https://adglob.in/blog/redis-pubsub-psubscribe-command/
Subscribes to channels matching the given patterns.
2PUBSUB subcommandhttps://adglob.in/blog/redis-sub-pubsub-command/
Tells the state of Pub/Sub system. For example, which clients are active on the server.
3PUBLISH channel messagehttps://adglob.in/blog/redis-pubsub-publish-command/
Posts a message to a channel.
4PUNSUBSCRIBE https://adglob.in/blog/redis-pubsub-punsubscribe-command/
Stops listening for messages posted to channels matching the given patterns.
5SUBSCRIBE https://adglob.in/blog/redis-pubsub-subscribe-command/
Listens for messages published to the given channels.
6UNSUBSCRIBE https://adglob.in/blog/redis-pubsub-unsubscribe-command/
Stops listening for messages posted to the given channels.

Leave a Reply