Latest web development tutorials

Redis publish and subscribe

Redis publish-subscribe (pub / sub) is a messaging mode: the sender (pub) to send a message, subscribers (sub) receive messages.

Redis client can subscribe to any number of channels.

The figure below shows the channel channel1, and subscribe to the channel three clients - the relationship client2, client5 and between client1:

pubsub1

When a new message is sent to the channel by channel1 PUBLISH command, this message will be sent to subscribe to its three clients:

pubsub2

Examples

The following example demonstrates how this works publish and subscribe. In our example we have created a subscription channel calledredisChat:

redis 127.0.0.1:6379> SUBSCRIBE redisChat

Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "redisChat"
3) (integer) 1

Now, let's re-open a redis client, and then publish redisChat message twice in the same channel, subscribers will be able to receive the message.

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 w3big.com"

(integer) 1

# 订阅者的客户端会显示如下消息
1) "message"
2) "redisChat"
3) "Redis is a great caching technique"
1) "message"
2) "redisChat"
3) "Learn redis by w3big.com"

Redis publish and subscribe command

The following table lists the redis publish subscribe commonly used commands:

No. Command and description
1 PSUBSCRIBE pattern [pattern ...]
Subscribe to one or more match a given pattern of channels.
2 PUBSUB subcommand [argument [argument ...] ]
View subscription and publishing system status.
3 PUBLISH channel message
The information is sent to the specified channel.
4 PUNSUBSCRIBE [pattern [pattern ...]]
Unsubscribe from all channels given pattern.
5 SUBSCRIBE channel [channel ...]
Subscribe to the information given to one or more channels.
6 UNSUBSCRIBE [channel [channel ...]]
It refers to unsubscribe from a given channel.