AMQP多任务处理

时间:2013-03-08 17:58:26

标签: ruby rabbitmq amqp eventmachine

我有一个有趣的情况,我需要实现。我需要有一个EventMachine循环,该循环位于并等待AMQP队列中的消息,但随后中断该循环,以便定期向单独的AMQP队列发送消息。我是EventMachine的新手,这是我到目前为止所做的,除了EventMachine循环不发送必要的消息。

现在我做了两个过程:

    listen_loop = Proc.new {
        AMQP.start(connection_config) do |connection|
            AMQP::Channel.new(connection) do |channel|
                channel.queue("queue1", :exclusive => false, :durable => true) do |requests_queue|
                    requests_queue.once_declared do
                        consumer = AMQP::Consumer.new(channel, requests_queue).consume
                        consumer.on_delivery do |metadata, payload|
                            puts "[requests] Got a request #{metadata.message_id}. Sending a reply to #{metadata.reply_to}..."
                            response = "responding"
                            channel.default_exchange.publish(response,
                                :routing_key    => metadata.reply_to,
                                :correlation_id => metadata.message_id,
                                :mandatory      => true)
                            metadata.ack
                        end
                    end
                end
            end
        end
        Signal.trap("INT")  { AMQP.stop { EM.stop } }
        Signal.trap("TERM") { AMQP.stop { EM.stop } }
    }

    send_message = Proc.new {
        AMQP.start(connection_config) do |connection|
            channel = AMQP::Channel.new(connection)
            queue   = channel.queue('queue2')

            channel.default_exchange.publish("hello world", :routing_key => queue.name)
            EM.add_timer(0.5) do
                connection.close do
                    EM.stop{ exit }
                end
            end
        end
    }

然后我有了EventMachine循环:

    EM.run do 
        EM.add_periodic_timer(5) { send_message.call }
        listen_loop.call
    end

我能够在listen循环中接收消息,但是我无法定期发送任何消息。

1 个答案:

答案 0 :(得分:0)

弄清楚我做错了什么。消息循环无法打开与RabbitMQ服务器的新连接,因为它已连接。将所有内容整合到一个EventMachine循环中并重用连接并且它可以正常工作。

对于那些好奇的人看起来像这样:

EM.run do

    AMQP.start(connection_config) do |connection|
        channel = AMQP::Channel.new(connection)

        EM.add_periodic_timer(5) { channel.default_exchange.publish("foo", :routing_key => 'queue2') }

        queue = channel.queue("queue1", :exclusive => false, :durable => true)
        channel.prefetch(1)
        queue.subscribe(:ack => true) do |metadata, payload|
            puts "[requests] Got a request #{metadata.message_id}. Sending a reply to #{metadata.reply_to}..."
            response = "bar"
            channel.default_exchange.publish(response,
                :routing_key    => metadata.reply_to,
                :correlation_id => metadata.message_id,
                :mandatory      => true)
            metadata.ack
        end
    end
    Signal.trap("INT")  { AMQP.stop { EM.stop } }
    Signal.trap("TERM") { AMQP.stop { EM.stop } }

end