How to use Redis publish and subscribe

Redis publish subscribe

In the publish-subscribe mode, the publisher is the publisher who publishes the message, and the subscriber who receives the message is the subscriber. In Redis, all messages are published through channels, that is, channels. A publisher can publish messages to multiple channels, and a subscriber can also subscribe to multiple channels. Redis does not persist messages. If the subscriber has not subscribed when the message is published, the message will not be received.

 

publish subscribe command

Order Format illustrate
PUBLISH PUBLISH channel message Publish the message to the specified channel
SUBSCRIBE SUBSCRIBE channel [channel ...] Subscribe to 1 or more specified channels
UNSUBSCRIBE UNSUBSCRIBE [channel [channel ...]] Unsubscribe from one or more specified channels. If no channel is specified, unsubscribe from all channels subscribed through SUBSCRIBE
PSUBSCRIBE PSUBSCRIBE pattern [pattern ...] Subscribe to channel based on matching pattern
PUNSUBSCRIBE PUNSUBSCRIBE [pattern [pattern ...]] Unsubscribe the channel according to the matching pattern, if the matching pattern is not specified, unsubscribe all channels subscribed through PSUBSCRIBE

 

subscribe cannot subscribe to the same channel repeatedly, and psubscribe may subscribe to the same channel multiple times when subscribing according to the matching pattern. If psubscribe subscribes to the same channel multiple times, after the publisher uses publish to publish a message to this channel, the subscriber will receive this message multiple times.

Unsubscribe can only unsubscribe from the channel subscribed by subscribe, and punsubscribe can only unsubscribe from the channel subscribed by psubscribe.

 

Instructions

1. Subscribe to the specified channel

192.168.1.100:6379> subscribe testchan
Reading messages... (press Ctrl-C to quit)
1) "subscribe" #Subscribe successfully
2) "testchan" #Subscribed channel name
3) (integer) 1 #Number of subscribed channels
 
1) "message" #Receive a message
2) "testchan" #source channel
3) "hello" #Message content
 
192.168.1.100:6379> publish testchan hello
(integer) 1 #Number of subscribers who received the message

 

 

2. Subscribe to the channel of the specified matching pattern

192.168.1.100:6379> psubscribe test*
Reading messages... (press Ctrl-C to quit)
1) "psubscribe" #Subscribe successfully
2) "test*" #Subscription channel matching pattern
3) (integer) 1 #Number of subscribed channel matching patterns
 
1) "pmessage" #Receive message
2) "test*" #matching subscription pattern
3) "testchan" #source channel
4) "hello" #Message content
 
192.168.1.100:6379> publish testchan hello
(integer) 1 #Number of subscribers who received the message

 


Original address: http://caiguoqing.org/post/110

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326712418&siteId=291194637