Redis之釋出與訂閱

stonebox1122發表於2017-08-11
訂閱者可以透過subscribe和psubscribe命令向redis server訂閱自己感興趣的訊息型別。redis將資訊型別稱為通道(channel)。當釋出者透過publish命令向redis server傳送特定型別的資訊時,訂閱該資訊型別的全備client都會收到此訊息。
會話1:監聽頻道1
127.0.0.1:6379> subscribe tv1
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "tv1"
3) (integer) 1

會話2:監聽頻道1和2
127.0.0.1:6379> subscribe tv1 tv2
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "tv1"
3) (integer) 1
1) "subscribe"
2) "tv2"
3) (integer) 2

會話3:在頻道1釋出資訊
127.0.0.1:6379> publish tv1 stone
(integer) 2

檢視會話1:
127.0.0.1:6379> subscribe tv1
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "tv1"
3) (integer) 1
1) "message"
2) "tv1"
3) "stone"

檢視會話2:
127.0.0.1:6379> subscribe tv1 tv2
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "tv1"
3) (integer) 1
1) "subscribe"
2) "tv2"
3) (integer) 2
1) "message"
2) "tv1"
3) "stone"


會話3:在頻道2釋出資訊
127.0.0.1:6379> publish tv2 stone2
(integer) 1

檢視會話2:
127.0.0.1:6379> subscribe tv1 tv2
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "tv1"
3) (integer) 1
1) "subscribe"
2) "tv2"
3) (integer) 2
1) "message"
2) "tv1"
3) "stone"
1) "message"
2) "tv2"
3) "stone2

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/28536251/viewspace-2143385/,如需轉載,請註明出處,否則將追究法律責任。

相關文章