Redis 發布訂閱模式及應用場景

2021-10-03 17:17:54 字數 2596 閱讀 1375

redis 發布訂閱(pub/sub)是一種訊息通訊模式:傳送者(pub)傳送訊息,訂閱者(sub)接收訊息。

命令描述

publish channel message

將資訊傳送到指定的頻道。

subscribe channel [channel …]

訂閱給定的乙個或多個頻道的資訊

psubscribe pattern [pattern …]

訂閱乙個或多個符合給定模式的頻道。

unsubscribe [channel [channel …]]

指退訂給定的頻道。

punsubscribe [pattern [pattern …]]

退訂所有給定模式的頻道。

2.1 如下,客戶機a訂閱了news頻道,客戶機b也訂閱了news頻道;客戶機c推送訊息時,客戶機a和客戶機b都能收到訊息。

(1)客戶機c傳送了訊息 helloworld

[root@localhost redis-4.0.8]

# redis-cli

127.0.0.1:6379> publish news helloworld!

(integer) 2

127.0.0.1:6379>

[root@localhost redis-4.0.8]

#

(2)客戶機a收到了訊息

[root@localhost ~]

# redis-cli

127.0.0.1:6379> subscribe news

reading messages...

(press ctrl-c to quit)

1)"subscribe"

2)"news"

3)(integer) 1

1)"message"

2)"news"

3)"helloworld!"

(3)客戶機b也收到了訊息

[root@localhost redis-4.0.8]

# redis-cli

127.0.0.1:6379> subscribe news

reading messages...

(press ctrl-c to quit)

1)"subscribe"

2)"news"

3)(integer) 1

1)"message"

2)"news"

3)"helloworld!"

2.2 如下,客戶機a訂閱了news.*頻道,客戶機b也訂閱了news.hello頻道;客戶機c推送訊息到頻道news.hello,客戶機d推送訊息到頻道news.world;客戶機a能收到客戶機c和客戶機d的訊息,而客戶機b只能收到客戶機c的訊息。

(1)客戶機c分別向頻道news.hello和news.world傳送了訊息

[root@localhost redis-4.0.8]

# redis-cli

127.0.0.1:6379> public news.hello

127.0.0.1:6379> publish news.hello goodmorining

(integer) 2

127.0.0.1:6379> publish news.world nihao

(integer) 1

127.0.0.1:6379>

(2)客戶機a接收了訊息

[root@localhost ~]

# redis-cli

127.0.0.1:6379> psubscribe news.

*reading messages...

(press ctrl-c to quit)

1)"psubscribe"

2)"news.*"

3)(integer) 1

1)"pmessage"

2)"news.*"

3)"news.hello"

4)"goodmorining"

1)"pmessage"

2)"news.*"

3)"news.world"

4)"nihao"

(3)客戶機b接收的訊息

[root@localhost redis-4.0.8]

# redis-cli

127.0.0.1:6379> subscribe news.hello

reading messages...

(press ctrl-c to quit)

1)"subscribe"

2)"news.hello"

3)(integer) 1

1)"message"

2)"news.hello"

3)"goodmorining"

1、構建實時訊息系統,比如普通的即時聊天,群聊等功能。

redis事務及鎖應用 發布訂閱模式

mysql和ridis事務對比 redis事務時執行命令放到了佇列裡。注 rollback與discard的區別 如果已經成功執行了2條語句,第三條語句出錯 rollback後前2條語句影響消失。discard只是結束本次事務,前2句造成的影響還在。注 在multi後面的語句中,語句出錯可能有2中情...

Redis發布訂閱模式

publish subscribe 發布訂閱模式的原理 包含兩個角色,乙個是發布者,乙個是訂閱者 訂閱者可以訂閱乙個或者多個頻道channel 發布者可以向指定頻道發布資訊 通過publish發布訊息 publish channel message publish channel1.1 maizie...

redis訂閱發布模式

理論遲點再補,先上 直接上 demopub.php 發布者 redis new redis redis connect localhost 6379 redis publish mcs 麒麟之才 demosub.php 訂閱者 redis new redis redis connect 127.0....