Skip to content

Instantly share code, notes, and snippets.

@sandersch
Last active December 19, 2015 02:09
Show Gist options
  • Save sandersch/5881248 to your computer and use it in GitHub Desktop.
Save sandersch/5881248 to your computer and use it in GitHub Desktop.
Bunny gem for AMQP Spike
require "bunny"
# Start a communication session with RabbitMQ
conn = Bunny.new
conn.start
# open a channel
ch = conn.create_channel
# declare a queue
q = ch.queue("test1")
# publish a message to the default exchange which then gets routed to this queue
q.publish("Hello, everybody!")
# fetch a message from the queue
delivery_info, metadata, payload = q.pop
puts "This is the message: #{payload}"
# close the connection
conn.stop
require "amqp"
require "yaml"
t = Thread.new { EventMachine.run }
sleep(0.5)
connection = AMQP.connect
channel = AMQP::Channel.new(connection, :auto_recovery => true)
channel.on_error do |ch, channel_close|
raise "Channel-level exception: #{channel_close.reply_text}"
end
channel.prefetch(1)
channel.queue("test1").subscribe do |metadata, payload|
puts "Received: #{payload}"
end
puts "[boot] Ready"
Signal.trap("INT") { connection.close { EventMachine.stop } }
t.join

AMQP

http://rubyamqp.info/articles/getting_started/

RabbitMQ

http://www.rabbitmq.com/download.html

Gems

AMQP Gem

Integrating with Unicorn

Bunny Gem

https://github.com/ruby-amqp/bunny

EventMachine

AMQP

  • Prefetch
  • Autodelete

Channels

Queues

  • Queues store and forward messages to consumers. Queues are like mailboxes in SMTP.
  • Messages are first delivered to exchanges which route messages to queues using rules called bindings.
  • Queues and binding are declared by apps.

Queue Attributes

  • Name
  • Durability
  • Whether the queue is auto-deleted when no longer used
  • Other metadata (sometimes called X-arguments)

Queue Naming

  • Queues contain several segments separated by a dot, like URI path segments and /
  • Before use, queue must be declared
    • Will be created if doesn't exist
    • No effect if queue already does exist and its attributes are the same as the declaration
    • Channel-level exception is raised if attributes don't match
    • e.g. to declare queue named "images.resize":
      queue = AMQP::Queue.new(channel, "images.resize", :auto_delete => true)
      

Exchanges

Durability

require "bunny"
# Start a communication session with RabbitMQ
conn = Bunny.new
conn.start
# open a channel
ch = conn.create_channel
# declare a queue
q = ch.queue("test1")
loop do
# publish a message to the default exchange which then gets routed to this queue
puts "Sending..."
q.publish("Hello, everybody!")
sleep 5
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment