ruby - AMQP 动态创建订阅队列

标签 ruby websocket amqp

我正在尝试使用 AMQP、Websockets 和 Ruby 构建一个简单的聊天应用程序。我知道这可能不是理解 AMQP 的最佳用例,但我想了解我哪里出错了。

以下是我的amqp-server代码

require 'rubygems'
require 'amqp'
require 'mongo'
require 'em-websocket'
require 'json'

class MessageParser
  # message format => "room:harry_potter, nickname:siddharth, room:members"
  def self.parse(message)
    parsed_message = JSON.parse(message)

    response = {}
    if parsed_message['status'] == 'status'
      response[:status] = 'STATUS'
      response[:username] = parsed_message['username']
      response[:roomname] = parsed_message['roomname']
    elsif parsed_message['status'] == 'message'
      response[:status]   = 'MESSAGE'
      response[:message]  = parsed_message['message']
      response[:roomname] = parsed_message['roomname'].split().join('_')
    end

    response
  end
end

class MongoManager
  def self.establish_connection(database)
    @db ||= Mongo::Connection.new('localhost', 27017).db(database)
    @db.collection('rooms')

    @db
  end  
end


@sockets = []
EventMachine.run do
  connection = AMQP.connect(:host => '127.0.0.1')
  channel = AMQP::Channel.new(connection)

  puts "Connected to AMQP broker. #{AMQP::VERSION} "

  mongo = MongoManager.establish_connection("trackertalk_development")

  EventMachine::WebSocket.start(:host => '127.0.0.1', :port => 8080) do |ws|
    socket_detail = {:socket => ws}
    ws.onopen do 
      @sockets << socket_detail

    end

    ws.onmessage do |message|

      status  = MessageParser.parse(message)         
      exchange = channel.fanout(status[:roomname].split().join('_'))   

      if status[:status] == 'STATUS'               
         queue = channel.queue(status[:username], :durable => true)

        unless queue.subscribed? 
         puts "--------- SUBSCRIBED --------------"
         queue.bind(exchange).subscribe do |payload|
            puts "PAYLOAD :  #{payload}"
            ws.send(payload)
          end 
        else
          puts "----ALREADY SUBSCRIBED"
        end                  

        # only after 0.8.0rc14
        #queue = channel.queue(status[:username], :durable => true)      
        #AMQP::Consumer.new(channel, queue)        

      elsif status[:status] == 'MESSAGE'
        puts "********************* Message- published ******************************"
        exchange.publish(status[:message)  
      end                  
    end

    ws.onclose do 
      @sockets.delete ws
    end
  end    
end

我使用状态来指示传入消息是用于正在进行的聊天的消息还是需要我处理诸如订阅队列之类的杂务的状态消息。

我面临的问题是,当我发送一条消息时 socket.send(JSON.stringify({status:'message', message:'test', roomname:'Harry Potter'}))

调用了 exchange.publish',但它仍然没有通过 ws.send` 推送到浏览器。

我对 EventMachine 和 AMQP 的理解有什么根本性的错误吗?

这是相同代码的馅饼http://pastie.org/private/xosgb8tw1w5vuroa4w7a

当我从 queue = channel.queue(status[:username], :durable => true) 中删除 durable => true 时,我的代码似乎可以正常工作>

以下是我的 Rails View 的片段,它识别用户的用户名和房间名称,并将其作为消息的一部分通过 Websockets 发送。

虽然当我删除 durable => true 时代码似乎可以工作,但我不明白为什么这会影响传递的消息。请忽略 mongo 部分,因为它还没有发挥任何作用。

我还想知道我对 AMQP 的方法及其用法是否正确

<script>
    $(document).ready(function(){
        var username = '<%= @user.email %>';
        var roomname = 'Bazingaa';

        socket = new WebSocket('ws://127.0.0.1:8080/');

        socket.onopen = function(msg){
            console.log('connected');
            socket.send(JSON.stringify({status:'status', username:username, roomname:roomname}));
        }

        socket.onmessage = function(msg){
            $('#chat-log').append(msg.data);

        }

    });

</script>
<div class='block'>
  <div class='content'>
    <h2 class='title'><%= @room.name %></h2>
    <div class='inner'>
      <div id="chat-log">
      </div>

      <div id="chat-console">
        <textarea rows="5" cols="40"></textarea>
      </div>
    </div>
  </div>
</div>

<style>
    #chat-log{
        color:#000;
        font-weight:bold;
        margin-top:1em;
        width:900px;
        overflow:auto;
        height:300px;
    }
    #chat-console{
        bottom:10px;
    }

    textarea{
        width:100%;
        height:60px;
    }
</style>

最佳答案

我认为您的问题可能是队列在 ws.onmessage 调用之间卡在代理上。当客户端重新连接队列并且绑定(bind)已经存在时,ws.send() 不会被调用。

默认情况下,当您创建一个队列时,它和它拥有的任何绑定(bind)都会挂起,直到代理重新启动,或者您明确告诉代理将其删除。

有两种方法可以改变这一点:

  • 在创建队列时添加 durable 标志,这将导致即使代理重新启动,队列仍然存在
  • 添加 auto_delete 标志,这将导致代理在短时间内没有消费者附加到实体后自动删除该实体

如果您可以控制您正在使用 rabbitmq 代理的代理,一个简单的方法来检查代理上发生的事情是安装 management plugin ,它为代理上的交换、绑定(bind)和队列提供了一个 Web 界面。

关于ruby - AMQP 动态创建订阅队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6747033/

相关文章:

ruby-on-rails - 如何让 TextMate 默认使用 Ruby on Rails?

jakarta-ee - 在 Java EE 的 WebSocket 端点中使路径参数可选

ssl - meteor / Apollo : SSL Access for HTTPS and WS?

django - RabbitMQ 保持连接运行很长时间

rabbitmq - 生产者/消费者的不同语言

ruby - Redis 多个请求

ruby-on-rails - 从多个 ActiveRecord 查询创建 Ruby 哈希的有效方法

带有 websockets 的 apache mod 代理平衡器

python - RabbitMQ 消费者停止接收消息

mysql - 如何使用 strftime 格式化查询日期