釋出訂閱
相關命令:publish(釋出) subscribe(訂閱) psubscribe(支援萬用字元匹配)
釋出者--頻道--訂閱者(釋出和訂閱都是客戶端頻道是服務端)
1、publish- subscribe 模式
開啟一個命令窗體,redis訂閱者:
# redis-cli 127.0.0.1:6379> subscribe channel_1 Reading messages... (press Ctrl-C to quit) 1) "subscribe" 2) "channel_1" 3) (integer) 1
然後再開啟一個命令窗體為redis 釋出者:
# redis-cli
127.0.0.1:6379> publish channel_1 "hello"
(integer) 2
127.0.0.1:6379> publish channel_1 "world"
(integer) 2
然後再看看訂閱者的反饋:
127.0.0.1:6379> subscribe channel_1 Reading messages... (press Ctrl-C to quit) 1) "subscribe" 2) "channel_1" 3) (integer) 1 1) "message"//訂閱訊息 2) "channel_1"//頻道 3) "hello"//訊息體 1) "message"//訊息 2) "channel_1"//訂閱頻道 3) "world"//訊息
收到 channle_1=>hello 和 channel_1=>world,釋出者廣播的訊息。
2、publish-psubscribe 模式
首先,定義訂閱者訂閱
# redis-cli
127.0.0.1:6379> psubscribe server-*
Reading messages... (press Ctrl-C to quit)
1) "psubscribe"
2) "server-*"
3) (integer) 1
其次,定義釋出者server-1
# redis-cli 127.0.0.1:6379> publish server-1 "server-1"
再次,定義釋出者server-2
# redis-cli 127.0.0.1:6379> publish server-2 "server_2"
最後,檢視訂閱者訂閱變化
# redis-cli 127.0.0.1:6379> psubscribe server-* Reading messages... (press Ctrl-C to quit) 1) "psubscribe" 2) "server-*" 3) (integer) 1 1) "pmessage" 2) "server-*" 3) "server-1"//server-1 4) "server-1" 1) "pmessage" 2) "server-*" 3) "server-2"//server-2 4) "server_2"
3、退訂
unsubscribe <頻道s>
punsubscribe <頻道s>
4、檢視訂閱資訊 PUBSUB CHANNELS