我填满了我的队列,检查它有正确数量的任务来工作,然后让工作人员并行设置,prefetch(1)
以确保每个人一次只接受一项任务。
我希望每个工作人员完成其任务,发送手动确认,并在有更多工作时继续工作。
如果没有更多工作,即队列为空,我希望工作脚本完成并且return(0)
.
所以,这就是我现在所拥有的:
require 'bunny'
connection = Bunny.new("amqp://my_conn")
connection.start
channel = connection.create_channel
queue = channel.queue('my_queue_name')
channel.prefetch(1)
puts ' [*] Waiting for messages.'
begin
payload = 'init'
until queue.message_count == 0
puts "worker working queue length is #{queue.message_count}"
_delivery_info, _properties, payload = queue.pop
unless payload.nil?
puts " [x] Received #{payload}"
raise "payload invalid" unless payload[/cucumber/]
begin
do_stuff(payload)
rescue => e
puts "Error running #{payload}: #{e.backtrace.join('\n')}"
#failing stuff
end
end
puts " [x] Done with #{payload}"
end
puts "done with queue"
connection.close
exit(0)
ensure
connection.close
end
当队列为空时,我仍然想确保我完成了。这是来自 RabbitMQ 站点的示例... https://www.rabbitmq.com/tutorials/tutorial-two-ruby.html。它为我们的工作队列提供了许多我们想要的东西,最重要的是手动确认。但它不会停止运行,我需要在队列完成后以编程方式发生:
#!/usr/bin/env ruby
require 'bunny'
connection = Bunny.new(automatically_recover: false)
connection.start
channel = connection.create_channel
queue = channel.queue('task_queue', durable: true)
channel.prefetch(1)
puts ' [*] Waiting for messages. To exit press CTRL+C'
begin
queue.subscribe(manual_ack: true, block: true) do |delivery_info, _properties, body|
puts " [x] Received '#{body}'"
# imitate some work
sleep body.count('.').to_i
puts ' [x] Done'
channel.ack(delivery_info.delivery_tag)
end
rescue Interrupt => _
connection.close
end
当队列完全工作(0 总和 0 未确认)时,如何调整此脚本以退出?