使用 redis 和 ruby​​ 发布/订阅消息传递

Joh*_*ino 2 ruby redis

我查看了这个文档:

\n\n

http://redis.io/topics/pubsub

\n\n

它指出:

\n\n

当您订阅频道时,您将收到一条消息,该消息表示为包含三个元素的批量回复。消息的第一个元素是消息的类型(例如SUBSCRIBE 或UNSUBSCRIBE)。消息的第二个元素是您正在订阅或取消订阅的给定频道的名称。消息的第三个元素是您当前订阅的频道数量:

\n\n
> SUBSCRIBE first second\n\n*3        #three elements in this message: \xe2\x80\x9csubscribe\xe2\x80\x9d, \xe2\x80\x9cfirst\xe2\x80\x9d, and 1\n$9        #number of bytes in the element \nsubscribe #kind of message\n$5        #number of bytes in the element \nfirst     #name of channel\n:1        #number of channels we are subscribed to\n
Run Code Online (Sandbox Code Playgroud)\n\n

这很酷,您可以在订阅频道的批量回复中看到您订阅的频道数量。现在我尝试在使用 ruby​​ 时得到此回复:

\n\n
require \'rubygems\'\nrequire \'redis\'\nrequire \'json\'\n\nredis = Redis.new(:timeout => 0)\n\nredis.subscribe(\'chatroom\') do |on|\n  on.message do |channel, msg, total_channels|\n    data = JSON.parse(msg)\n    puts "##{channel} - [#{data[\'user\']}]: #{data[\'msg\']} - channels subscribed to: #{total_channels}"\n  end\nend\n
Run Code Online (Sandbox Code Playgroud)\n\n

然而,我根本没有得到这样的答复。它给我的是通道的名称,发布到该通道的数据,然后total_channels为nil,因为没有发回第三个参数。

\n\n

那么redis所说的“多批量回复”在哪里呢?

\n

Did*_*zia 5

实际上,该协议是在订阅操作之后发送订阅回复消息作为第一条消息。您不会在收到的所有消息中获得订阅频道的数量(就像订阅/取消订阅的回复一样)。

使用当前版本的 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
Run Code Online (Sandbox Code Playgroud)

请注意,在您的示例中,订阅数量始终为 1。