Blog

Filter posts by Category Or Tag of the Blog section!

Basic producer and consumer by RabitMQ in .Net

Thursday, 12 April 2018

RabitMQ is one of the most popular queue messages in the development world. In the basic form, for producing or so-called sending a message or an object into the queue you can use BasicPublish of the channel you have connected. As you can see in the following picture after sending the message to the queue, you can consume or so-called retrieve the message.

 

After installing erlang and rabitMQ in your machine, create a console application and copy and paste the following code!

 class Program
    {
        static void Main(string[] args)
        {
            Producer();
            Consumer();
        }

        public static void Producer()
        {
            var factory = new ConnectionFactory() { HostName = "localhost" };
            using (var connection = factory.CreateConnection())
            using (var channel = connection.CreateModel())
            {
                channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null);

                string message = "Thid first element of the channel!";
                var body = Encoding.UTF8.GetBytes(message);

                channel.BasicPublish(exchange: "", routingKey: "hello", basicProperties: null, body: body);
                Console.WriteLine(" [x] Sent {0}", message);
            }
        }

        public static void Consumer()
        {
            var factory = new ConnectionFactory() { HostName = "localhost" };
            using (var connection = factory.CreateConnection())
            using (var channel = connection.CreateModel())
            {
                channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null);

                Console.WriteLine(" [*] Waiting for messages.");

                var consumer = new EventingBasicConsumer(channel);

                consumer.Received += (model, ea) =>
                {
                    var body = ea.Body;
                    var message = Encoding.UTF8.GetString(body);
                    Console.WriteLine(" [x] Received {0} successfully", message);
                };

                channel.BasicConsume(queue: "hello", autoAck: true, consumer: consumer);

                Console.WriteLine(" Press enter to exit.");
                Console.ReadLine();
            }
        }
    }

Rather than BasicPublish, there is also a BasicConsume to get the message from queue! This was just a simple usage of RabitMQ. I will post some advanced usages of RabitMQ in the future.

 

Category: Software

Tags: RabitMQ

comments powered by Disqus