Objectives
This sample demonstrates how durable or non-durable topics can be created and used in Message Broker using the RabbitMQ .Net/C# client. It first introduces a sample .Net client by the name "TopicPublisher" which is used to publish messages to a known, created topic in WSO2 Message Broker, and then introduces a sample .Net client by the name "TopicConsumer" to listen on messages and print message content in console.
Prerequisites
In order to run this code sample, you need to download and add RabbitMQ.Client.dll file as a reference in your .net project. You can download that dll file from this website http://www.rabbitmq.com/dotnet.html or here.
Running the Sample
Prior to running following "TopicPublisher" class we need to register at least one " TopicConsumer" binding prior sending messages to the topic. This can be done by either,
- Logging into WSO2 Message Broker management console and create a topic named 'test-topic' ("Topics -> Add" menu in the "Main" menu).
- Run " TopicConsumer " class depicted below. It will register a binding to that topic. When you have run the TopicConsumer code you will see topic subscription created by the TopicConsumer class is visible in the management console ("Topics -> Browse").
Now using the following "TopicPublisher" .Net client, messages can be sent to 'test-topic' created earlier.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using RabbitMQ.Client; namespace MB_Topic_Publisher { class TopicPublisher { static void Main(string[] args) { TopicPublisher topicPublisher = new TopicPublisher(); topicPublisher.PublishMessage("Test Message"); Console.WriteLine("Message Sent.."); Console.ReadLine(); } public void PublishMessage(string message) { //Setup the connection with the message broker ConnectionFactory factory = new ConnectionFactory(); IProtocol protocol = Protocols.AMQP_0_8_QPID; factory.VirtualHost = "/carbon"; factory.UserName = "admin"; factory.Password = "admin"; factory.HostName = "localhost"; factory.Port = 5672; factory.Protocol = protocol; using (IConnection conn = factory.CreateConnection()) { using (IModel ch = conn.CreateModel()) { // Declare a topic exchange to publish messages, here we have used the default topic exchange of WSO2 MB ch.ExchangeDeclare("amq.topic", "topic"); //Publish the message to the exchange, it will send it to the routing key which is our name 'myTopic'. The syntax is ch.BasicPublish(<exchange_name>, <topic_name>, <message_properties>,<message_body>) ch.BasicPublish("amq.topic", "myTopic", null, Encoding.UTF8.GetBytes(message)); } } } } }