Thinks todo before start:
- RabbitMQ server must be installed
- If you want to install RabbitMQ, the Erlang/OTP must be installed in your machine
- RabbitMQ service must be start before run the application
- RabbitMQ.Client package must be install on your corresponding project
How to start the RabbitMQ service:
There are two ways to start the RabbitMQ service on your machine
- The one is go to service.msc and start the RabbitMQ service
- Another one is All Programs > RabbitMQ server > RabbitMQ Service Start
If you are not start the RabbitMQ service:
ConnectionFactory
for RabbitMQ client is not able to create the connection
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.HostName =
hostName;
// this
will fail If you are not start the RabbitMQ service.
Connection =
connectionFactory.CreateConnection();
Major namespaces, interfaces and classes:
using RabbitMQ.Client;
using RabbitMQ.Client.Exceptions;
The core API interfaces and classes are:
- Imodel
- Iconnection
- ConnectionFactory
- IBasicConsumer
Basic properties for ConnectionFactory to create connection are:
- UserName
- Password
- HostName
- VirtualHost
Create
the connection:
protected IModel Model;
protected IConnection Connection;
protected string QueueName;
ConnectionFactory factory = new ConnectionFactory();
factory.UserName
= “guest”;
//
"gue
factory.Password
= “guest”;
factory.VirtualHost
= “/”;
factory.HostName =
“hello”;
Connection = connectionFactory.CreateConnection();
Model = Connection.CreateModel();
Model.QueueDeclare(QueueName, false, false, false, null);
Publishing Messages:
IBasicProperties basicProperties = Model.CreateBasicProperties();
Model.BasicPublish("", QueueName, basicProperties, message);
Retrieving Messages:
Create Consumer to
retrieving the messages
QueueingBasicConsumer consumer = new QueueingBasicConsumer(Model);
String consumerTag = Model.BasicConsume(QueueName, false, consumer);
try
{
RabbitMQ.Client.Events.BasicDeliverEventArgs e
= (RabbitMQ.Client.Events.BasicDeliverEventArgs)consumer.Queue.Dequeue();
IBasicProperties props =
e.BasicProperties;
byte[] body = e.Body;
// ... process the message
onMessageReceived(body);
Model.BasicAck(e.DeliveryTag, false);
}
catch (OperationInterruptedException ex)
{
// The consumer was removed, either through
// channel or connection closure, or through the
// action of IModel.BasicCancel().
break;
}