2013-07-27 40 views
1

短信我看了看這個文檔:發佈/訂閱與Redis的和紅寶石

http://redis.io/topics/pubsub

它指出:

當您訂閱的頻道,你會得到被表示爲一個消息多元批量回復三個要素。消息的第一個元素是消息的類型(例如SUBSCRIBE或UNSUBSCRIBE)。消息的第二個元素是您正在訂閱或取消訂閱的給定頻道的名稱。該消息的第三個因素是目前你訂閱的信道的數目:

> SUBSCRIBE first second 

*3  #three elements in this message: 「subscribe」, 「first」, and 1 
$9  #number of bytes in the element 
subscribe #kind of message 
$5  #number of bytes in the element 
first  #name of channel 
:1  #number of channels we are subscribed to 

這是涼爽你可以看到你訂閱從訂閱頻道的堆積答覆的一部分信道的數目。現在我試圖在使用紅寶石時得到這個回覆:

require 'rubygems' 
require 'redis' 
require 'json' 

redis = Redis.new(:timeout => 0) 

redis.subscribe('chatroom') do |on| 
    on.message do |channel, msg, total_channels| 
    data = JSON.parse(msg) 
    puts "##{channel} - [#{data['user']}]: #{data['msg']} - channels subscribed to: #{total_channels}" 
    end 
end 

但是,我根本沒有得到那種答覆。它給我的是頻道的名稱,發佈到該頻道的數據,然後total_channels爲零,因爲沒有第三個參數被髮回。

那麼redis提到的這個「多批量答覆」在哪裏?

回答

2

實際上,協議是在訂閱操作之後發送訂閱回覆消息作爲第一條消息。在收到的所有郵件中,您都沒有收到訂閱頻道的數量(只是作爲對訂閱/取消訂閱的回覆)。

隨着Redis的-RB的當前版本,你需要一個單獨的處理器來處理訂閱/退訂回覆消息:

require 'rubygems' 
require 'redis' 
require 'json' 

redis = Redis.new(:timeout => 0) 

redis.subscribe('chatroom') do |on| 
    on.subscribe do |channel, subscriptions| 
     puts "Subscribed to ##{channel} (#{subscriptions} subscriptions)" 
    end 
    on.message do |channel, msg| 
     data = JSON.parse(msg) 
     puts "##{channel} - [#{data['user']}]: #{data['msg']}" 
    end 
end 

請注意,在你的榜樣,用戶數量將始終爲1