Kanina
A Rails plugin that makes it easier for your models to communicate with RabbitMQ.
Kanina abstracts away queue and exchange creation, so you can focus on the message and subscription side of things in Rails.
Prerequisites
You'll need RabbitMQ installed. Find instructions for your platform here.
Installation
Put this in your Gemfile
:
gem 'kanina'
Then run bundle install
to install the gem and its dependencies. Finally, run rails generate kanina:install
to create bin/kanina and an amqp.yml.sample file in your config folder.
Copy amqp.yml.sample to amqp.yml, and change it to connect to your local RabbitMQ server. By default, it will connect to the one on your development machine, as long as you haven't changed the settings on it.
Sending Messages
Run the generator:
rails generate kanina:message MessageName
Then specify the name of the exchange, OR the routing key for the intended queue. To send a message, generate an instance of your new class, add data, and hit send:
msg = MessageName.new
msg.data = {key: "value"}
msg.deliver
You can also specify the type of exchange you want to create, like so:
class WeatherMessage < Kanina::Message
fanout "reports"
end
Remember to use RabbitMQ's documentation to understand the rules governing how to use different types of exchanges, bindings, and queues appropriately. You don't have to create those things ahead of time with Kanina, but you do have to understand how they work!
Receiving messages
Generate a subscription with this command:
rails generate kanina:subscription SubscriptionName
Then tweak the resulting file to attach to the right queue, or use bindings to watch a named exchange. Use a subscribe block to define code that you want run when a message is received:
class NotifyUserSubscription < Kanina::Subscription
subscribe queue: "notify_user" do |data|
User.where(id: data[:id]).first.notify
end
end
This project was written by Clinton Judy, and uses the ISC license.