📜  Redis-发布订阅

📅  最后修改于: 2020-11-26 07:04:58             🧑  作者: Mango


Redis Pub / Sub实现了消息传递系统,其中发件人(用redis术语称为发布者)发送消息,而接收者(订户)接收消息。传输消息的链接称为channel

在Redis中,客户端可以订阅任意数量的频道。

以下示例说明了发布订户概念的工作方式。在以下示例中,一个客户端订阅了一个名为“ redisChat”的频道。

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

现在,两个客户端正在名为“ redisChat”的同一通道上发布消息,并且上述订阅的客户端正在接收消息。

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 tutorials point"  
(integer) 1   
1) "message" 
2) "redisChat" 
3) "Redis is a great caching technique" 
1) "message" 
2) "redisChat" 
3) "Learn redis by tutorials point" 

Redis PubSub命令

下表列出了一些与Redis Pub / Sub相关的基本命令。

Sr.No Command & Description
1 PSUBSCRIBE pattern [pattern …]

Subscribes to channels matching the given patterns.

2 PUBSUB subcommand [argument [argument …]]

Tells the state of Pub/Sub system. For example, which clients are active on the server.

3 PUBLISH channel message

Posts a message to a channel.

4 PUNSUBSCRIBE [pattern [pattern …]]

Stops listening for messages posted to channels matching the given patterns.

5 SUBSCRIBE channel [channel …]

Listens for messages published to the given channels.

6 UNSUBSCRIBE [channel [channel …]]

Stops listening for messages posted to the given channels.