diff --git a/sylvilagus/jruby/lib/sylvilagus/ch02/hello_world.rb b/sylvilagus/jruby/lib/sylvilagus/ch02/hello_world.rb index 0991495..1b0441b 100644 --- a/sylvilagus/jruby/lib/sylvilagus/ch02/hello_world.rb +++ b/sylvilagus/jruby/lib/sylvilagus/ch02/hello_world.rb @@ -6,15 +6,16 @@ import com.rabbitmq.client.ConnectionFactory module Sylvilagus::Ch02::HelloWorld module ClassMethods - def with_hello_world_conn(&block) + def with_hello_world_channel(&block) factory = ConnectionFactory.new factory.uri = ENV.fetch('SYLVILAGUS_AMQP_URI') conn = factory.new_connection + channel = conn.create_channel channel.exchange_declare('hello-exchange', 'direct', true) channel.queue_declare('hello-queue', false, false, false, nil) - block.call(conn, channel) + block.call(channel) ensure conn.close end diff --git a/sylvilagus/jruby/lib/sylvilagus/ch02/hello_world_consumer.rb b/sylvilagus/jruby/lib/sylvilagus/ch02/hello_world_consumer.rb index 6eaf54d..ab528a1 100644 --- a/sylvilagus/jruby/lib/sylvilagus/ch02/hello_world_consumer.rb +++ b/sylvilagus/jruby/lib/sylvilagus/ch02/hello_world_consumer.rb @@ -8,21 +8,34 @@ class Sylvilagus::Ch02::HelloWorldConsumer < DefaultConsumer include Sylvilagus::Ch02::HelloWorld::ClassMethods def main - with_hello_world_conn do |conn,channel| - channel.basic_consume('hello-queue', false, new(channel)) + with_hello_world_channel do |channel| + consumer = new(channel) + + STDERR.puts 'Starting consume loop...' + channel.basic_consume('hello-queue', false, consumer) + loop do - sleep 3 - puts "Still waiting..." + sleep 1 + break if consumer.done? end end end end + def done? + @done ||= false + end + def handleDelivery(consumer_tag, envelope, properties, body) - delivery_tag = envelope.get_delivery_tag body_string = RubyString.bytes_to_string(body) + puts "Consumed #{body_string.inspect}" - get_channel.basic_ack(delivery_tag, false) + channel.basic_ack(envelope.delivery_tag, false) + + if body_string == 'quit' + STDERR.puts 'Quitting...' + @done = true + end end end diff --git a/sylvilagus/jruby/lib/sylvilagus/ch02/hello_world_producer.rb b/sylvilagus/jruby/lib/sylvilagus/ch02/hello_world_producer.rb index 66c4610..5397775 100644 --- a/sylvilagus/jruby/lib/sylvilagus/ch02/hello_world_producer.rb +++ b/sylvilagus/jruby/lib/sylvilagus/ch02/hello_world_producer.rb @@ -4,9 +4,10 @@ class Sylvilagus::Ch02::HelloWorldProducer class << self include Sylvilagus::Ch02::HelloWorld::ClassMethods - def main - message = ARGV.first || 'snorg' - with_hello_world_conn do |conn,channel| + def main(args = ARGV.clone) + raise 'Missing message arg!' if args.empty? + message = args.fetch(0) + with_hello_world_channel do |channel| channel.basic_publish('hello-exchange', 'hola', nil, message.to_java_bytes) puts "Published #{message.inspect}" end @@ -15,5 +16,5 @@ class Sylvilagus::Ch02::HelloWorldProducer end if $0 == __FILE__ - Sylvilagus::Ch02::HelloWorldProducer.main + Sylvilagus::Ch02::HelloWorldProducer.main(ARGV) end