由於我的大部分任務都依賴於網絡,因此我希望並行處理隊列,而不是一次處理一條消息。Ruby + AMQP:並行處理隊列
所以,我用下面的代碼:
#!/usr/bin/env ruby
# encoding: utf-8
require "rubygems"
require 'amqp'
EventMachine.run do
connection = AMQP.connect(:host => '127.0.0.1')
channel = AMQP::Channel.new(connection)
channel.prefetch 5
queue = channel.queue("pending_checks", :durable => true)
exchange = channel.direct('', :durable => true)
queue.subscribe(:ack => true) do |metadata, payload|
time = rand(3..9)
puts 'waiting ' + time.to_s + ' for message ' + payload
sleep(time)
puts 'done with '+ payoad
metadata.ack
end
end
爲什麼不使用我的預讀設置?我想它應該得到5條消息,並行處理它們,不是嗎?
費爾南多,在我看來,joelparkerhenderson的答案在下面很有用。它有助於解決您的問題嗎?讓我們知道任何一種方式。 –