Adding the picture resizing consumer

This commit is contained in:
Dan Buch 2012-11-26 23:42:08 -05:00
parent b3f0f5c4ec
commit 10aa737d1d

View File

@ -0,0 +1,63 @@
require 'sylvilagus/init'
require 'sylvilagus/ch04'
require 'json'
require 'rabbitmq-client.jar'
class Sylvilagus::Ch04::ResizePictureConsumer
class Consumer < Java::ComRabbitmqClient::DefaultConsumer
def handleDelivery(consumer_tag, envelope, properties, body)
message = Java::OrgJruby::RubyString.bytes_to_string(body)
if message == 'quit'
channel.basic_cancel(consumer_tag)
@done = true
return
end
message_hash = JSON.parse(message)
resize_picture(message_hash.fetch('image_id'),
message_hash.fetch('image_path'))
channel.basic_ack(envelope.delivery_tag, false)
rescue StandardError
channel.basic_nack(envelope.delivery_tag, false)
end
def resize_picture(image_id, image_path)
puts "Resizing picture: #{image_id} #{image_path}"
end
def done?
!!@done
end
end
def main
factory = Java::ComRabbitmqClient::ConnectionFactory.new
factory.uri = ENV.fetch('SYLVILAGUS_AMQP_URI')
@conn = factory.new_connection
channel = @conn.create_channel
channel.exchange_declare(
'upload-pictures', 'fanout', false, true, false, nil
)
channel.queue_declare('resize-picture', false, true, false, nil)
channel.queue_bind('resize-picture', 'upload-pictures', '')
consumer = Consumer.new(channel)
puts "Consuming from 'upload-pictures' exchange"
channel.basic_consume('resize-picture', false,
"resize-picture-consumer-#{$$}-#{ENV['HOSTNAME']}",
false, false, nil, consumer)
loop do
break if consumer.done?
sleep 1
end
return 0
ensure
@conn.close if @conn
end
end
if $0 == __FILE__
exit Sylvilagus::Ch04::ResizePictureConsumer.new.main
end