Commit a0cd0ce

mo khan <mo@mokhan.ca>
2014-10-10 17:17:43
add example using direct exchange and routing keys.
1 parent c9892aa
Changed files (2)
lib/4-routing/publish.rb
@@ -0,0 +1,17 @@
+#!/usr/bin/env ruby
+## encoding: utf-8
+
+require "bunny"
+
+connection = Bunny.new
+connection.start
+
+channel = connection.create_channel
+exchange = channel.direct("direct_logs")
+severity = ARGV.shift || "info"
+message = ARGV.empty? ? "Hello World!" : ARGV.join(" ")
+
+exchange.publish(message, routing_key: severity)
+puts " [x] Sent '#{message}'"
+
+connection.close
lib/4-routing/subscribe.rb
@@ -0,0 +1,30 @@
+#!/usr/bin/env ruby
+## encoding: utf-8
+
+require "bunny"
+
+if ARGV.empty?
+  abort "Usage: #{$0} [info] [warning] [error]"
+end
+
+connection = Bunny.new
+connection.start
+
+channel = connection.create_channel
+exchange = channel.direct("direct_logs")
+queue = channel.queue("", exclusive: true)
+
+ARGV.each do |severity|
+  queue.bind(exchange, routing_key: severity)
+end
+
+puts " [*] Waiting for logs. To exit press CTRL+C"
+
+begin
+  queue.subscribe(block: true) do |delivery_info, properties, body|
+    puts " [x] #{delivery_info.routing_key}:#{body}"
+  end
+rescue Interrupt => _
+  channel.close
+  connection.close
+end