Redis系列(三)—— 訂閱/發布

來源:互聯網
上載者:User

標籤:res   comm   查看   str   語言   www   htm   即時   令行   

Redis 訂閱/發布

參考:http://www.cnblogs.com/mushroom/p/4470006.html,http://www.tuicool.com/articles/ABry2aj,http://www.cnblogs.com/tinywan/p/5903256.html,http://www.cnblogs.com/linjiqin/p/5733183.html,http://redisbook.readthedocs.io/en/latest/feature/pubsub.html

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

Redis 用戶端可以訂閱任意數量的頻道。

展示了頻道 channel1 , 以及訂閱這個頻道的三個用戶端 —— client2 、 client5 和 client1 之間的關係:

當有新訊息通過 PUBLISH 命令發送給頻道 channel1 時, 這個訊息就會被發送給訂閱它的三個用戶端:

執行個體

以下執行個體示範了發布訂閱是如何工作的。在我們執行個體中我們建立了訂閱頻道名為 redisChat:

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

 

現在,我們先重新開啟個 redis 用戶端,然後在同一個頻道 redisChat 發布兩次訊息,訂閱者就能接收到訊息。

redis 127.0.0.1:6379> PUBLISH redisChat "Redis is a great caching technique"(integer) 1redis 127.0.0.1:6379> PUBLISH redisChat "Learn redis by runoob.com"(integer) 1# 訂閱者的用戶端會顯示如下訊息1) "message"2) "redisChat"3) "Redis is a great caching technique"1) "message"2) "redisChat"3) "Learn redis by runoob.com"

 

Redis 發布訂閱命令

下表列出了 redis 發布訂閱常用命令:

序號 命令及描述
1 PSUBSCRIBE pattern [pattern ...] 訂閱一個或多個符合給定模式的頻道。
2 PUBSUB subcommand [argument [argument ...]] 查看訂閱與發布系統狀態。
3 PUBLISH channel message 將資訊發送到指定的頻道。
4 PUNSUBSCRIBE [pattern [pattern ...]] 退訂所有給定模式的頻道。
5 SUBSCRIBE channel [channel ...] 訂閱給定的一個或多個頻道的資訊。
6 UNSUBSCRIBE [channel [channel ...]] 指退訂給定的頻道。

 

PHP實現

訂閱端:sub.php

$redis = new Redis();
$res = $redis->pconnect(‘127.0.0.1‘, 6379,0);
$redis->auth(‘123456‘);

$channel = $argv[1];  // channel
$redis->subscribe(array(‘channel‘.$channel), ‘callback‘);
function callback($instance, $channelName, $message) {
  echo $channelName, "==>", $message,PHP_EOL;
}

使用方法: (命令列操作)

php sub.php test

注釋:test為訂閱channel

 

發布端:pub.php

$redis = new Redis();
// 第一個參數為redis伺服器的ip,第二個為連接埠
$res = $redis->connect(‘127.0.0.1‘, 6379);
//Auth
$redis->auth(‘123456‘);

$channel = $argv[1];  // channel
$msg = $argv[2]; // msg
$redis->publish(‘channel‘.$channel, $msg);

使用方法: (命令列操作)

php pub.php test ‘msg‘

注釋:test為訂閱channel,msg為發送訊息

 

過程:

訂閱,啟動後,會即時監聽和響應

發布

 

其他語言,比如java,Python,參考:http://blog.csdn.net/freebird_lb/article/details/7778959,http://guozhiwei.iteye.com/blog/1240600

 

Redis系列(三)—— 訂閱/發布

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.