Send message from C# to rabbitMQ

For first download and install the .NET/C# AMQP client library

On Visual Studio, include the RabbitMQ.Client reference import the library into the class:

using RabbitMQ.Client;
using RabbitMQ.Client.Framing.v0_8;

At this point initialise the queue and connection to the RabbitMQ broker in the constructor:

var connectionFactory = new ConnectionFactory();
connectionFactory.HostName = HostName;
Connection = connectionFactory.CreateConnection();
Model = Connection.CreateModel();
Model.QueueDeclare(QueueName, false, false, false, null);

Now the connection factory and model are definied and is possible to send a message to the queue called “QueueName”:

IBasicProperties basicProperties = Model.CreateBasicProperties();
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Model.BasicPublish("", QueueName, basicProperties, encoding.GetBytes(message));

Note that BasicPublish use byte[] for the message. The parameters are:

BasicPublish(String exchange, String routingKey, IBasicProperties basicProperties, byte[] body)

Leave a Reply