我有一个有趣的情况需要完成。我需要有一个 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
我能够在监听循环中接收消息,但我无法定期发送任何消息。