Sunday, 14 December 2014

Rails and RabbitMQ RPC

Integrate Ruby on Rails with RabbitMQ RPC

This post shows how to implement RabbitMQ RPC using Ruby on Rails. 
I have implemented the RabbitMQ Request-Response pattern. This is the standard request/response pattern used by messaging systems. The client sends a request and then blocks until a response is received. The client creates a callback queue for the response and matches the response using a correlation id. An RPC worker written in Ruby is waiting for requests and acts as the server.



This is my implementation of the RabbitMQ tutorial shown at www.rabbitmq.com ruby tutorial six.  I have used the bunny gem to connect to rabbitMQ.  My project has been uploaded to GitHub at RailsRabbit. Most of the client and server source code can be found in rabbitmixin.rb.

I added the following code to my create method in my controller to access RabbitMQ using bunny and my rabbitmixin.  The controller creates a connection, channel, client and sends a message, waits for a response and then closes the channel and connection.

The client creates a uuid to be used as a correlation id, a lock to wait for the response and sends the message.  When the message is sent the reply queue is set to wait for the response and then returned to the calling controller.

The server waits for a message, reads the message, reverses it and then sends it back on the reply queue set by the client and also sets the correlation id.


The following ruby script is used to start the server process and waits for requests.

The ruby server is started using command:
$ ruby -rubygems rpc_server.rb

I found it really easy to get Rails integrated to RabbitMQ and running.  I am impressed with how quick I got the app working, much better than some messaging systems I have used in the past.



No comments:

Post a Comment