在我的ROR应用程序中,我有一个要求,即我需要使用来自一个交换机的消息,然后在向头部附加一些额外数据后将其发布到另一个交换机。所以我创建了一个rake任务来启动AMQP。
EventMachine.run do
$configurations = Config.new.config
rmq_configurations = Config.new.rmq
connection = AMQP.connect(rmq_configurations)
$channel = AMQP::Channel.new(connection)
puts "AMQP listening"
worker = MessageHandler.new
puts "Message handler started"
worker.start
end
在Message处理程序类中,我已经定义了交换,如下所示
def initialize
@ns_exchange = $configurations["ns_exchange"]
@sc_exchange = $configurations["sc_exchange"]
@ns_queue = $configurations["ns_queue"]
@sc_queue = $configurations["sc_queue"]
end
def start
@ns_x = $channel.direct(ns_exchange, :durable => true)
@sc_x = $channel.direct(sc_exchange, :durable => true)
@ns_queue = $channel.queue(ns_queue, :auto_delete => true)
@ns_queue.bind(@ns_x, :routing_key => "ipam").subscribe(&method(:handle_ns_message))
message_headers = {"messageType" => "ipam/operations/ip/checkCanAllocateIP"}
message_body = {"ipsToAllocate" => "1", "orgId" => "438c6cdd-aa2d-4f3c-bec3-aefb85d6fca5"}
@ns_x.publish(message_body, :routing_key => "ipam", :headers => message_headers, :mandatory => true)
@sc_queue = ch2.queue(sc_queue, :auto_delete => true)
@sc_queue.bind(@sc_x, :routing_key => @sc_queue.name).subscribe(&method(:handle_sc_message))
@sc_x.publish(message_body, :routing_key => "ipam", :headers => message_headers, :mandatory => true)
end
只有在我有一次交换时,发布才有效。此外,我永远不想关闭连接,因为AMQP需要始终运行以消耗&产生消息
答案 0 :(得分:0)
我为每个交易所创建单独的渠道后能够发布消息