我正在使用RabbitMQ和ruby-amqp和Rails。当控制器收到消息时,我执行以下操作:
def create
AMQP.start("amqp://localhost:5672") do |connection|
channel = AMQP::Channel.new(connection)
exchange = channel.direct("")
exchange.publish("some msg", :routing_key => "some key")
EventMachine.add_timer(2) do
exchange.delete
connection.close { EventMachine.stop }
end
end
end
start
?我认为打开与Rabbit MQ的连接是低效的,但是我没有找到将代码块传递给持久连接的方法。
答案 0 :(得分:1)
如果您只想保持AMQP连接打开,请尝试设置全局变量以保持连接唯一。
def start_em
EventMachine.run do
$connection = AMQP.connect(CONNECTION_SETTING) unless $connection
yield
end
end
def publish(message, options = {})
start_em {
channel = AMQP::Channel.new($connection)
exchange = channel.direct('')
exchange.publish(message, {:routing_key => 'rails01'}.merge(options))
EventMachine.add_timer(1) { exchange.delete }
}
end
不要忘记在留言后删除频道。