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:

http://www.erlang.org/download.html  (Windows Binary File)

http://www.rabbitmq.com/server.html  (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}]}]"}

rabbitmq-config


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

rabbitmq-admin


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


image


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

Username:  guest
Password:  guest

rabbit-web 

Setting up RabbitMQ


Add an Exchange of type “direct”


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


image


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.


image


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


image


Finally add a binding per queue


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

image


image


The Workflow


image


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
}, ORDER_ROUTING_KEY);

Source


http://stevenhollidge.com/blog-source-code/RabbitMQ-Workflow.zip

2 comments: