Class: Kanina::Subscription
- Inherits:
-
Object
- Object
- Kanina::Subscription
- Extended by:
- Logger
- Defined in:
- lib/kanina/subscription.rb
Overview
Kanina::Subscription
allows you to automatically receive messages
from RabbitMQ, and run a block of code upon receiving each new message.
Queues and bindings are set up on the fly. Subscriptions are also eagerly
loaded by Rails, so they're defined when the Rails environment is loaded.
Example:
# app/messages/user_message.rb class UserSubscription < Kanina::Subscription subscribe(bind: "user.exchange") do |data| puts data end end
Messages are depacked from JSON, into plain old Ruby objects. If you use
Kanina::Message
to send messages, it automatically encapsulates messages
into JSON to make the process easier.
Constant Summary
Constants included from Logger
Class Method Summary collapse
-
.channel ⇒ Bunny::Channel
Helper method to return the channel that Kanina::Server is talking on.
-
.create_binding(name, durable: false) ⇒ Object
Ensures the named exchange exists, and binds the queue to it.
-
.create_queue(name, durable: false) ⇒ Bunny::Queue
Creates the queue or attaches to the existing queue.
-
.subscribe(queue: '', bind: nil, durable: false) {|data| ... } ⇒ Object
Begins subscribing to the specified queue (or binds to an exchange and sets up an anonymous queue).
Methods included from Logger
Class Method Details
.channel ⇒ Bunny::Channel
Helper method to return the channel that Kanina::Server is talking on.
24 25 26 |
# File 'lib/kanina/subscription.rb', line 24 def channel Kanina::Server.channel or fail 'Kanina::Server.channel is not open' end |
.create_binding(name, durable: false) ⇒ Object
Ensures the named exchange exists, and binds the queue to it.
57 58 59 60 61 62 |
# File 'lib/kanina/subscription.rb', line 57 def create_binding(name, durable: false) if name.present? ensure_exchange_exists(name, durable: durable) @queue.bind(name) end end |
.create_queue(name, durable: false) ⇒ Bunny::Queue
Creates the queue or attaches to the existing queue. This will also create a random queue if the queue supplied is an empty string.
50 51 52 |
# File 'lib/kanina/subscription.rb', line 50 def create_queue(name, durable: false) @queue = channel.queue(name, durable: durable) end |
.subscribe(queue: '', bind: nil, durable: false) {|data| ... } ⇒ Object
Begins subscribing to the specified queue (or binds to an exchange and sets up an anonymous queue). The block is called for every message received, and data is passed in as a plain Ruby hash.
36 37 38 39 40 41 42 |
# File 'lib/kanina/subscription.rb', line 36 def subscribe(queue:'', bind:nil, durable:false, &blk) create_queue(queue, durable: durable) create_binding(bind, durable: durable) @queue.subscribe do |delivery_info, properties, body| yield format_data(body) end end |