Sunday, 29 April 2012

RabbitMQ C# Pub/Sub

RabbitMQ   Burrow

In this blog post I’ll show how to set up RabbitMQ on a Windows7 machine and create a C# pub/sub workflow application using Burrow.NET.

Unable to display content. Adobe Flash is required.

Installing up RabbitMQ

Download and install Erlang and then RabbitMQ:  (Windows Binary File)  (Installer for Windows systems)

Configuring RabbitMQ

Create the following file:  C:\Users\{username}\AppData\Roaming\RabbitMQ\rabbitmq.config

{"[{listeners,     [{mgmt, [{port, 55672}]}]},
{default_listener, [{port, 55670}]},
{contexts, [{rabbit_mgmt, mgmt}]}]"}


Open a command prompt and run the following commands:

cd C:\Program Files (x86)\RabbitMQ Server\rabbitmq_server-2.8.0\sbin
rabbitmq-plugins enable rabbitmq_management
rabbitmq-service.bat install


Open Services and configure your RabbitMQ service as per your preferences (startup type and logon account).  Make sure the service is started.


RabbitMQ is now installed as a service with the web management portal available at http://localhost:55672

Username:  guest
Password:  guest


Setting up RabbitMQ

Add an Exchange of type “direct”

Select the Exchange tab and scroll down to add a new Exchange.


Add a Queue per message type

Select the Queue tab and scroll down to add a new Queue for “Durable” durability.

Naming convention:  Burrow.Queue.{SubscriptionName}.{MessageType}

The message type is the serialisable C# object you’ll be publishing to the queue.


Note: The Burrow.Queue.Error will be automatically generated if required


Finally add a binding per queue

Click on a queue in the list then add a binding to the exchange.



The Workflow


C# Pub/Sub with Burrow.NET

Burrow.NET is available from NuGest, here is how to use it:

string QUEUE_CONNECTION_STRING = "host=localhost;username=guest;password=guest";
string ORDER_ROUTING_KEY = "Order";

// set up rabbitmq tunnel
ITunnel tunnel = RabbitTunnel.Factory.Create(QUEUE_CONNECTION_STRING);
tunnel.SetSerializer(new JsonSerializer());

// sub
// where the named method interacts with the UI
// "Workflow" is used as the subscription name within the queue Burrow.Queue.Workflow.OrderMessage
var subscriptionOrder = tunnel.SubscribeAsync<OrderMessage>("Workflow",
(message, args) => Dispatcher.BeginInvoke(new Action(() => OnOrderReceived(message, args))));

// pub
tunnel.Publish(new OrderMessage
OrderId = orderId,
OrderDate = DateTime.Now,
ProductCode = "ABCDE",
Quantity = 10,
UnitPrice = 9.99m