Redis publish subscribe

Applicable scene

  • Live news
  • barrage message
  • Fan subscription news push

Knowledge point

1. Keywords: PUBLISH SUBSCRIBE PSUBSCRIBE

  • Redis uses the PUBLISH command to send messages, and the return value is the number of subscribers who received the message.
  • Redis uses the SUBSCRIBE command to subscribe to a channel. The return value includes the channel subscribed by the client, the number of channels currently subscribed, and the received message, where subscribe indicates that a channel has been successfully subscribed.

2. Example:

redis 127.0.0.1:6379> PUBLISH  c1 "test"
(integer) 0

redis 127.0.0.1:6379> PUBLISH  c2 "test"
(integer) 0
redis 127.0.0.1:6379> SUBSCRIBE c1
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "c1"
3) (integer) 1

1) "message"
2) "c1"
3) "test"

Redis's subscription operation is blocking, so once a client subscribes to a channel or pattern, it will remain subscribed until it exits.

3. Support pattern matching
Clients can use the command PSUBSCRIBE to subscribe to multiple channels matching pattern matching at one time, for example:

redis 127.0.0.1:6379> PSUBSCRIBE c*
Reading messages... (press Ctrl-C to quit)
1) "psubscribe"
2) "c*"
3) (integer) 1

1) "pmessage"
2) "c*"
3) "c2"
4) "test2"

c*Indicates any cchannel that starts with.

4. Note:

  • Subscribers can pre-book even if the channel doesn't exist.
  • Subscribers can only receive messages after subscription, not messages before subscription.

refer to

1. Redis publish and subscribe mechanism - yitudake - Blog Park
https://www.cnblogs.com/yitudake/p/6747995.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325073747&siteId=291194637
Recommended