![](/img/trans.png)
[英]Alternative for Redis SUB/PUB in Ruby for publish and subscribe events
[英]publish/subscribe messaging with redis and ruby
我查看了以下文檔:
它指出:
訂閱頻道后,您會收到一條消息,該消息表示為包含三個元素的多批回復。 消息的第一個元素是消息的種類(例如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
太酷了,您可以看到訂閱頻道的數量是批量回復(從訂閱頻道開始)的一部分。 現在,我嘗試使用ruby時獲得此回復:
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為nil,因為沒有發送回第三參數。
那么,redis所說的“多批答復”在哪里?
實際上,協議是在訂閱操作之后立即發送訂閱回復消息作為第一條消息。 您不會在收到的所有消息中獲得已訂閱頻道的數量(僅作為對已訂閱/取消訂閱的回復)。
使用當前版本的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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.