Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Table of Contents
maxLevel3
minLevel3

Introduction

This sample demonstrates how durable or non-durable topics can be created and used in WSO2 Message Broker using the RabbitMQ .NET/C# client. It first introduces a sample .NET client named named TopicPublisher, that publishes messages to a known, created topic in Message Broker. Then it introduces a sample .NET client named named TopicConsumer that  that listens for messages and prints message contents to the console.

Table of Contents
maxLevel3
minLevel3

Prerequisites

To run this sample:

...

Building the sample

  1. Create a TopicConsumer .NET NET client to receive messages from the test-topic topic by adding a class with the following code.

    Code Block
    languagejava
    /*using *System;
     Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
    *
    *  WSO2 Inc. licenses this file to you under the Apache License,
    *  Version 2.0 (the "License"); you may not use this file except
    *  in compliance with the License.
    *  You may obtain a copy of the License at
    *
    *    http://www.apache.org/licenses/LICENSE-2.0
    *
    * Unless required by applicable law or agreed to in writing,
    * software distributed under the License is distributed on an
    * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    * KIND, either express or implied.  See the License for the
    * specific language governing permissions and limitations
    * under the License.
    */
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using RabbitMQ.Client;
     
    namespace MB_TopicClient
    {
        class TopicConsumer
        {using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using RabbitMQ.Client;
     
    namespace MB_TopicClient
    {
        class TopicConsumer
        {
            static void Main(string[] args)
            {
                TopicConsumer topicConsumer = new TopicConsumer();
                topicConsumer.GetMessages();
            }
     
            public void GetMessages()
            {
                //Setup the connection with the message broker
                ConnectionFactory factory = new ConnectionFactory();
                IProtocol protocol = Protocols.AMQP_0_9_1;
                staticfactory.VirtualHost void Main(string[] args)= "/carbon";
                factory.UserName {= "admin";
               TopicConsumer topicConsumerfactory.Password = new TopicConsumer()"admin";
                topicConsumer.GetMessages()factory.HostName = "localhost";
            }    factory.Port = 5672;
         public void GetMessages()     factory.Protocol = protocol;
       {         using (IConnection conn  //Setup the connection with the message broker= factory.CreateConnection())
                {
         ConnectionFactory factory = new ConnectionFactory();       using (IModel ch = conn.CreateModel())
     IProtocol protocol = Protocols.AMQP_0_9_1;            {
    factory.VirtualHost = "/carbon";             factory.UserName = "admin";   // Declare a topic exchange to be bound to retrieve factory.Password = "admin";
           messages, here we have used the default topic exchange of WSO2 MB
        factory.HostName  = "localhost";             factory.Port = 5672ch.ExchangeDeclare("amq.topic", "topic");
                factory.Protocol = protocol;      // Declare a topic name, here we usinguse (IConnection conn = factory.CreateConnection())
            a non-durable topic. To make it durable use the 2nd parameter as 'true'  
     {                 using (IModel ch = conn.CreateModel())
       QueueDeclare("test-topic", false, false, false, null);
                {        // Bind the Topic in to the exchange
         // Declare a topic exchange to be bound to retrieve messages, here we have used the default topic exchange of WSO2 MB ch.QueueBind("test-topic", "amq.topic", "test-topic");
                        // Declare a consumer  ch.ExchangeDeclare("amq.topic", "topic");
                which listens on the messages published to 'test-topic' topic, we need to declare an exclusive subscriber, in order to get this work.
           // Declare a topic name, here we use a non-durable topic. To make it// durableThe usesyntax the 2nd parameter as 'true'  is BasicConsume(<queuename>, <noAck>,<consumerTag>, <noLocal>, <exclusive>, <arguments>, <Consumer>)
                        ch.QueueDeclare("test-topic", false, false, false, nullQueueingBasicConsumer consumer = new QueueingBasicConsumer(ch);
                        // Bind the Topic in to the exchangech.BasicConsume("test-topic", false, "1", false, true, null, consumer);
                        while ch.QueueBind("test-topic", "amq.topic", "test-topic");(true)
                        {
      // Declare a consumer which listens on the messages published to 'test-topic' topic, we need to declare an exclusive subscriber, in order totry
    get this work.                     // The{
    syntax is BasicConsume(<queuename>, <noAck>,<consumerTag>, <noLocal>, <exclusive>, <arguments>, <Consumer>)                     QueueingBasicConsumer consumer = new QueueingBasicConsumer(chRabbitMQ.Client.Events.BasicDeliverEventArgs e = (RabbitMQ.Client.Events.BasicDeliverEventArgs)consumer.Queue.Dequeue();
                        ch.BasicConsume("test-topic", false, "1", false, true, null, consumer);  byte[] body = e.Body;
                   while (true)            string message = Encoding.UTF8.GetString(body);
         {                       Console.WriteLine("Received Message try: " + message);
                         {         ch.BasicAck(e.DeliveryTag, false);
                       RabbitMQ.Client.Events.BasicDeliverEventArgs e = (RabbitMQ.Client.Events.BasicDeliverEventArgs)consumer.Queue.Dequeue();  }
                            catch  byte[] body = e.Body;(OperationCanceledException e)
                            {
          string message = Encoding.UTF8.GetString(body);                             Console.WriteLine("Received Message : " + messagee);
                                ch.BasicAck(e.DeliveryTag, false)break;
                            }
                        }
       catch (OperationCanceledException e)           }
                }
    {        }
                        Console.WriteLine(e);
                                break;
                            }
                        }
                    }
                }
            }
        }
    }
    Info

    At least one TopicConsumer binding should exist before sending messages to the topic. Therefore, this TopicConsumer class should be run before the TopicPublisher class. Alternatively, you can manually create the test-topic topic in the MB Management Console. See Adding Topics for detailed instructions.

    Create a TopicPublisher .NET client to send messages to the test-topic topic by adding a class with the following code.

    Code Block
    languagejava
    /*
    *  Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
    *
    *  WSO2 Inc. licenses this file to you under the Apache License,
    *  Version 2.0 (the "License"); you may not use this file except
    *  in compliance with the License.
    *  You may obtain a copy of the License at
    *
    *    http://www.apache.org/licenses/LICENSE-2.0
    *
    * Unless required by applicable law or agreed to in writing,
    * software distributed under the License is distributed on an
    * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    * KIND, either express or implied.  See the License for the
    * specific language governing permissions and limitations
    * under the License.
    */
    }
    }
    Info

    At least one TopicConsumer binding should exist before sending messages to the topic. Therefore, this TopicConsumer class should be run before the TopicPublisher class. Alternatively, you can manually create the test-topic topic in the MB Management Console. See Adding Topics for detailed instructions.

  2. Create a TopicPublisher .NET client to send messages to the test-topic topic by adding a class with the following code.

    Code Block
    languagejava
    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_9_1;
                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");
                        IBasicProperties basicProperties = ch.CreateBasicProperties();
                        //Setting JMS Message ID.
                        basicProperties.MessageId = "ID:" + System.Guid.NewGuid().ToString();
                        //Setting content-type for message as we are sending a text message.
                        basicProperties.ContentType = "text/plain";
                        // 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", "test-topic", basicProperties, Encoding.UTF8.GetBytes(message));
                    }
                }
            }
        }
    }
  3. Add a Main.java class defining the method to call both the classes mentioned above.

Executing the sample

Run this sample from your C# project.