khunemz
1/19/2017 - 10:21 AM

Program.cs

Program.cs

using RabbitMQ.Client;
using System;

namespace RabbitMqSignalR
{
    internal class Program
    {
        private const string QueueName = "Testmessage";
        private const string ExchangeName = "ChatExchange";
        private static ConnectionFactory _factory;
        private static IConnection _rabbitMqConnection;
        private static IModel _rabbitMqModel;

        private static void Main(string[] args)
        {
            DeclareQueue();
            for (var i = 0; i < 20000; i++)
            {
                var rnd = new Random();
                var userId = rnd.Next(1, 3);
                Console.WriteLine("No. " + i + ", UserId : " + userId);

                var chat = new Chat();
                chat.Message = "Message number " + i + " : by userId " + userId;
                chat.EmptyMessage = "Empty Message number " + i + "  : by userId " + userId;
                chat.UserId = userId;

                // Add to queue
                SendToQueue(chat);
            }

            ReceiveQueue();
            Console.ReadKey();
        }

        private static void ReceiveQueue()
        {
            var consumer = new QueueingBasicConsumer(_rabbitMqModel);

            var chatCount = GetChatCount(_rabbitMqModel, QueueName);

            _rabbitMqModel.BasicConsume(QueueName, true, consumer);

            var repo = new ChatRepository();

            var count = 0;
            while (count < chatCount)
            {
                var chat = (Chat)consumer.Queue.Dequeue().Body.DeSerialize(typeof(Chat));
                repo.Save(chat);
                count++;
            }
            //return (Chat)consumer.Queue.Dequeue().Body.DeSerialize(typeof(Chat));
        }

        private static uint GetChatCount(IModel rabbitMqModel, string queueName)
        {
            var results = rabbitMqModel.QueueDeclare(queueName, true, false, false, null);
            return results.MessageCount;
        }

        private static void SendToQueue(Chat chat)
        {
            _rabbitMqModel.BasicPublish("", QueueName, null, chat.Serialize());
        }

        // Todo : Have to enable RabbitMQ server before
        private static void DeclareQueue()
        {
            _factory = new ConnectionFactory { HostName = "localhost", UserName = "khunemz", Password = "123123" };
            _rabbitMqConnection = _factory.CreateConnection();
            _rabbitMqModel = _rabbitMqConnection.CreateModel();
            _rabbitMqModel.QueueDeclare(QueueName, true, false, false, null);
        }

        private static void DeclareExchange()
        {
            // Fill implementation if there is any exchange
        }
    }
}