我正在使用 RabbitMQ 和 ruby-amqp与 Rails。当 Controller 收到消息时,我执行以下操作:
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 的连接效率低下,但是我还没有找到将代码块传递给持久连接的方法。
最佳答案
如果您只想保持 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
并且不要忘记在发布消息后删除 channel 。
关于rabbitmq - 使用 Ruby-Amqp 时如何保持 AMQP 连接打开?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10827666/