Example #1
0
        public static void Main2(string[] args)
        {
            ConnectionFactory factory    = TestUtilitiesClass.GetConnectionFactory();
            IConnection       connection = factory.CreateConnection();
            IModel            channel    = connection.CreateModel();

            channel.ExchangeDeclare(exchange: "topic_logs", type: "topic");
            string queueName = channel.QueueDeclare().QueueName;

            foreach (string bindingKey in args)
            {
                channel.QueueBind(queue: queueName,
                                  exchange: "topic_logs",
                                  routingKey: bindingKey);
            }

            Console.WriteLine("[*] Waiting for messages. To exit press CTRL+C");

            EventingBasicConsumer consumer = new EventingBasicConsumer(channel);

            consumer.Received += (model, ea) =>
            {
                byte[]          body            = ea.Body;
                RabbitMqMessage rabbitMqMessage = TestUtilitiesClass.ParseMessage(body);
                string          routingKey      = ea.RoutingKey;
                Console.WriteLine("[x] Received '{0}':'{1}'",
                                  routingKey,
                                  rabbitMqMessage.ToJsonString());
                TestUtilitiesClass.SleepProducer();
            };
            channel.BasicConsume(queue: queueName,
                                 autoAck: true,
                                 consumer: consumer);
        }
Example #2
0
        public static void Start(int count)
        {
            TaskFactory taskFactory = new TaskFactory();
            Action      action      = () =>
            {
                ConnectionFactory factory = TestUtilitiesClass.GetConnectionFactory();
                using (IConnection connection = factory.CreateConnection())
                {
                    using (IModel channel = connection.CreateModel())
                    {
                        IBasicProperties properties = channel.CreateBasicProperties();
                        properties.Persistent = true;
                        channel.QueueDeclare(queue: "MessageAcknowledgment",
                                             durable: false,
                                             exclusive: false,
                                             autoDelete: false,
                                             arguments: null);
                        for (int i = 0; i < count; i++)
                        {
                            byte[]          body = TestUtilitiesClass.GetMessage(i.ToString());
                            RabbitMqMessage item = TestUtilitiesClass.ParseMessage(body);
                            channel.BasicPublish(exchange: "",
                                                 routingKey: "MessageAcknowledgment",
                                                 basicProperties: properties,
                                                 body: body);
                            Console.WriteLine("Queued {0}", item.ToJsonString());
                            Console.WriteLine("");
                            Thread.Sleep(TimeSpan.FromSeconds(0.5));
                        }
                    }
                }
            };

            taskFactory.StartNew(action);
        }
Example #3
0
        private Message WaitReply(RabbitMqMessage originalPublishedMessage, string replyQueue, TimeSpan timeout)
        {
            var timeoutAt = DateTime.Now.Add(timeout);

            while (true)
            {
                if (DateTime.Now > timeoutAt)
                {
                    throw new TimeoutException();
                }

                var reply = Model.BasicGet(replyQueue, false);

                if (reply == null)
                {
                    continue;
                }
                if (reply.BasicProperties.CorrelationId != originalPublishedMessage.CorrelationId)
                {
                    continue;
                }


                Model.BasicAck(reply.DeliveryTag, false);

                Model.QueueDelete(replyQueue);

                return(reply.AsRabbitMqMessage().AsWcfMessage(
                           Parent.MaxReceivedMessageSize,
                           Parent.BufferManager,
                           Parent.EncoderFactory));
            }
        }
Example #4
0
        public static void Main2()
        {
            TestUtilitiesClass.PrintThreadId("Worker.Main2 (Consumer)");
            ConnectionFactory factory    = TestUtilitiesClass.GetConnectionFactory();
            IConnection       connection = factory.CreateConnection();
            IModel            channel    = connection.CreateModel();

            channel.QueueDeclare(queue: "task_queue",
                                 durable: true,
                                 exclusive: false,
                                 autoDelete: false,
                                 arguments: null);

            channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);

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

            EventingBasicConsumer consumer = new EventingBasicConsumer(channel);

            consumer.Received += (model, ea) =>
            {
                byte[]          body            = ea.Body;
                RabbitMqMessage rabbitMqMessage = TestUtilitiesClass.ParseMessage(body);

                Console.WriteLine("[Worker] Received {0} ThreadId: {1}", rabbitMqMessage.ToJsonString(), Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(TimeSpan.FromSeconds(1));
                Console.WriteLine("[Worker] Done");
                channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
            };

            channel.BasicConsume(queue: "task_queue",
                                 autoAck: false,
                                 consumer: consumer);
        }
        private void Consumer_RabbitReceived(RabbitMqMessage message, string consumer)
        {
            switch (message.Action)
            {
            case RabbitMqAction.GetAll:

                RabbitMqMessage getall = new RabbitMqMessage()
                {
                    Action = RabbitMqAction.Data,
                    Data   = articleRepository.Get()
                };

                this.consumer.Send(message.Sender + ".exchange", getall);
                Console.WriteLine("RabbitMQ: Articles Returned.");
                break;

            case RabbitMqAction.Delete:
                Article article = JsonConvert.DeserializeObject <Article>(message.Data.ToString());
                articleRepository.Delete(article.Id);
                Console.WriteLine("RabbitMQ: Article Deleted.");
                break;

            default:
                Console.WriteLine("Unknown RabbitMQ Message.");
                break;
            }
        }
Example #6
0
        public static void Main2()
        {
            TestUtilitiesClass.PrintThreadId("ReceiveLogs");
            ConnectionFactory factory    = TestUtilitiesClass.GetConnectionFactory();
            IConnection       connection = factory.CreateConnection();
            IModel            channel    = connection.CreateModel();

            channel.ExchangeDeclare(exchange: "logs", type: "fanout");
            string queueName = channel.QueueDeclare().QueueName;

            channel.QueueBind(queue: queueName,
                              exchange: "logs",
                              routingKey: "");
            Console.WriteLine(" [*] Waiting for logs.");
            EventingBasicConsumer consumer = new EventingBasicConsumer(channel);

            consumer.Received += (model, ea) =>
            {
                byte[]          body            = ea.Body;
                RabbitMqMessage rabbitMqMessage = TestUtilitiesClass.ParseMessage(body);
                Console.WriteLine("[ReceiveLogs]: {0}", rabbitMqMessage.ToJsonString());
                TestUtilitiesClass.SleepConsumer();
            };
            channel.BasicConsume(queue: queueName,
                                 autoAck: true,
                                 consumer: consumer);
        }
Example #7
0
        private static async Task SendMessagesAsync(
            IRabbitMqPublisher rabbitMqPublisher,
            int count,
            Exchange exchange,
            RoutingKey routingKey,
            ConcurrentBag <Exception> exceptions)
        {
            var guid = Guid.NewGuid();

            try
            {
                for (var i = 0; i < count; i++)
                {
                    var rabbitMqMessage = new RabbitMqMessage(
                        $"{guid}-{i}",
                        new Metadata(),
                        exchange,
                        routingKey,
                        new MessageId(Guid.NewGuid().ToString("D")));
                    await rabbitMqPublisher.PublishAsync(CancellationToken.None, rabbitMqMessage).ConfigureAwait(false);
                }
            }
            catch (Exception e)
            {
                exceptions.Add(e);
            }
        }
        public virtual IEnumerable <IBatchContainer> FromQueueMessage(RabbitMqMessage message, long sequenceId)
        {
            message.RequeueOnFailure = true;

            var batchContainer = Deserialize(message.Body);

            batchContainer.EventSequenceToken = new EventSequenceToken(sequenceId);
            return(new[] { batchContainer });
        }
Example #9
0
        public void RequestArticles()
        {
            Console.WriteLine("Requesting Articles");
            RabbitMqMessage message = new RabbitMqMessage()
            {
                Action = RabbitMqAction.GetAll
            };

            consumer.Send("Article.exchange", message);
        }
Example #10
0
 public RabbitMqRequestContext(Message message, RabbitMqReplyChannel parent, RabbitMqMessage currentMqMessage)
 {
     RequestMessage    = message;
     _Parent           = parent;
     _CurrentMqMessage = currentMqMessage;
     _Aborted          = false;
     _State            = CommunicationState.Opened;
     _ThisLock         = new object();
     _Model            = _Parent.Connection.CreateModel();
 }
Example #11
0
        public async Task QueueMessageBatchAsync <T>(Guid streamGuid, string streamNamespace, IEnumerable <T> events, StreamSequenceToken token, Dictionary <string, object> requestContext)
        {
            if (token != null)
            {
                throw new ArgumentException("RabbitMq stream provider does not support non-null StreamSequenceToken.", nameof(token));
            }

            RabbitMqMessage message = _dataAdapter.ToQueueMessage(streamGuid, streamNamespace, events, token, requestContext);

            await _producer.Value.SendAsync(message);
        }
Example #12
0
        /// <inheritdoc cref="IPublisher.Publish"/>
        public void Publish(IMessage message)
        {
            var wrappingObject = new RabbitMqMessage
            {
                Id   = message.GetType().Name,
                Data = message
            };
            var serializedEvent = JsonSerializer.Serialize(wrappingObject);
            var body            = Encoding.UTF8.GetBytes(serializedEvent);

            _rabbitMqModel.BasicPublish(_exchangeName, "", null, body);
        }
Example #13
0
        public bool WaitForRequest(TimeSpan timeout)
        {
            ThrowIfDisposedOrNotOpen();

            var basicGet = Model.BasicGet(ServiceConfiguration.ServiceQueue, false);

            while (basicGet == null)
            {
                Thread.Sleep(_GetInterval);
                basicGet = Model.BasicGet(ServiceConfiguration.ServiceQueue, false);
            }

            _CurrentRabbitMqMessage = basicGet.AsRabbitMqMessage();

            return(true);
        }
Example #14
0
        private void DeleteArticle(Article article)
        {
            RabbitMqMessage message = new RabbitMqMessage()
            {
                Action = RabbitMqAction.Delete,
                Data   = article
            };

            consumer.Send("Article.exchange", message);

            message = new RabbitMqMessage()
            {
                Action = RabbitMqAction.Delete,
                Data   = article.Id
            };

            consumer.Send("Vote.exchange", message);
        }
        public IEnumerable <WeatherForecast> Get()
        {
            const string queueName = "Queue Test";

            var x = Activity.Current;

            var objToSend = new Dictionary <string, string> {
                { "msg", "Ricardo Test" }
            };
            var message = new RabbitMqMessage(objToSend, queueName);

            _publisher.PublishMessage(message);

            _publisher.PublishBatchMessages(new List <RabbitMqMessage>()
            {
                new(objToSend, queueName),
                new(objToSend, queueName)
            });
        public virtual RabbitMqMessage ToQueueMessage <T>(Guid streamGuid, string streamNamespace, IEnumerable <T> events, StreamSequenceToken token, Dictionary <string, object> requestContext)
        {
            var container  = new RabbitMqBatchContainer(streamGuid, streamNamespace, events.Cast <object>().ToList(), requestContext);
            var serialized = Serialize(container);

            var queueName = _topologyProvider.GetNameForQueue(_mapper.GetQueueForStream(streamGuid, streamNamespace));

            var message = new RabbitMqMessage
            {
                Body                 = serialized,
                Exchange             = string.Empty,
                RoutingKey           = queueName,
                Persistent           = true,
                ShouldConfirmPublish = true,
            };

            return(message);
        }
Example #17
0
        // consumer.Received event not firing when channel.BasicConsume is called
        // https://groups.google.com/forum/#!topic/rabbitmq-users/l0GQ4w3sYEU
        public static void HandleMessage(string readerName)
        {
            ConnectionFactory     factory    = TestUtilitiesClass.GetConnectionFactory();
            IConnection           connection = factory.CreateConnection();
            IModel                channel    = connection.CreateModel();
            EventingBasicConsumer consumer   = new EventingBasicConsumer(channel);

            consumer.Received += (model, ea) =>
            {
                byte[]          body    = ea.Body;
                RabbitMqMessage message = TestUtilitiesClass.ParseMessage(body);
                Console.WriteLine($"[{readerName}] Received {message.ToJsonString()}");
                Console.WriteLine("");
                Thread.Sleep(TimeSpan.FromSeconds(1));
            };
            Console.WriteLine($"BasicConsume: {readerName} ThreadId: " + Thread.CurrentThread.ManagedThreadId);
            Console.WriteLine("");
            channel.BasicConsume(queue: "round_robin", autoAck: true, consumer: consumer);
        }
        public void ShouldExecuteHelloWorldCommand()
        {
            using (var receiver = new RabbitMqSubscriber <RabbitMqMessage <HelloWorldCommand> >(new RabbitMqConfig())) {
                receiver.Subscribe(AssertReceivedMessage);

                var message = new RabbitMqMessage <HelloWorldCommand> {
                    Payload = new HelloWorldCommand {
                        Input = "Hola!"
                    }
                };
                var dispatcher = container.Resolve <ICommandDispatcher>();
                dispatcher.SubmitRabbitMqCommand(message);

                while (!messageReceived)
                {
                    log.Info("Waiting for a message receiver");
                }
            }
        }
Example #19
0
        public static void Main2(string severity)
        {
            TestUtilitiesClass.PrintThreadId("EmitLogDirect");
            ConnectionFactory factory = TestUtilitiesClass.GetConnectionFactory();

            using (IConnection connection = factory.CreateConnection())
                using (IModel channel = connection.CreateModel())
                {
                    channel.ExchangeDeclare(exchange: "direct_logs", type: ExchangeType.Direct);

                    byte[]          body            = TestUtilitiesClass.GetMessage("EmitLogDirect " + severity);
                    RabbitMqMessage rabbitMqMessage = TestUtilitiesClass.ParseMessage(body);
                    channel.BasicPublish(exchange: "direct_logs",
                                         routingKey: severity,
                                         basicProperties: null,
                                         body: body);
                    Console.WriteLine("[EmitLogDirect] Sent '{0}':'{1}'", severity, rabbitMqMessage);
                    TestUtilitiesClass.SleepProducer();
                }
        }
        private void Consumer_RabbitReceived(RabbitMqMessage message, string consumer)
        {
            switch (message.Action)
            {
            case RabbitMqAction.Delete:
                int articleId            = int.Parse(message.Data.ToString());
                IEnumerable <Vote> votes = voteRepository.GetArticle(articleId);

                foreach (Vote vote in votes)
                {
                    voteRepository.Delete(vote.Id);
                }

                Console.WriteLine("RabbitMQ: " + votes.Count() + " votes Deleted.");
                break;

            default:
                Console.WriteLine("Unknown RabbitMQ Message.");
                break;
            }
        }
Example #21
0
        public IAsyncResult BeginWaitForRequest(TimeSpan timeout, AsyncCallback callback, object state)
        {
            ThrowIfDisposedOrNotOpen();

            var asyncResult = new GenericAsyncResult(false, state, timeout, callback, false);

            var consumer = new EventingBasicConsumer(Model);

            consumer.Received += (a, b) =>
            {
                asyncResult.Complete();

                _CurrentRabbitMqMessage = b.AsRabbitMqMessage();

                callback?.Invoke(asyncResult);
            };

            Model.BasicConsume(ServiceConfiguration.ServiceQueue, false, consumer);

            return(asyncResult);
        }
Example #22
0
        public static void Main2(int count)
        {
            TestUtilitiesClass.PrintThreadId("EmitLog");
            ConnectionFactory factory = TestUtilitiesClass.GetConnectionFactory();

            using (IConnection connection = factory.CreateConnection())
                using (IModel channel = connection.CreateModel())
                {
                    channel.ExchangeDeclare(exchange: "logs", type: ExchangeType.Fanout);
                    byte[]          body            = TestUtilitiesClass.GetMessage("PuttingItAllTogetherConsole");
                    RabbitMqMessage rabbitMqMessage = TestUtilitiesClass.ParseMessage(body);
                    for (int i = 0; i < count; i++)
                    {
                        channel.BasicPublish(exchange: "logs",
                                             routingKey: "",
                                             basicProperties: null,
                                             body: body);
                        Console.WriteLine("Sent {0}", rabbitMqMessage.ToJsonString());
                        TestUtilitiesClass.SleepProducer();
                    }
                }
        }
Example #23
0
        public static void Main2(int counter)
        {
            TestUtilitiesClass.PrintThreadId("FanoutLogsProducer.Main2");
            ConnectionFactory factory = TestUtilitiesClass.GetConnectionFactory();

            using (IConnection connection = factory.CreateConnection())
                using (IModel channel = connection.CreateModel())
                {
                    channel.ExchangeDeclare("logs", ExchangeType.Fanout);
                    channel.QueueDeclare("logA",
                                         durable: false,
                                         exclusive: false,
                                         autoDelete: false);
                    channel.QueueDeclare("logB",
                                         durable: false,
                                         exclusive: false,
                                         autoDelete: false);
                    channel.QueueDeclare("logC",
                                         durable: false,
                                         exclusive: false,
                                         autoDelete: false);
                    channel.QueueBind("logA", "logs", "");
                    channel.QueueBind("logB", "logs", "");
                    channel.QueueBind("logC", "logs", "");
                    byte[]          message         = TestUtilitiesClass.GetMessage("FanoutLogsProducer");
                    RabbitMqMessage rabbitMqMessage = TestUtilitiesClass.ParseMessage(message);

                    for (int i = 0; i < counter; i++)
                    {
                        channel.BasicPublish(exchange: "logs",
                                             routingKey: "",
                                             basicProperties: null,
                                             body: message);
                        Console.WriteLine("Published: " + rabbitMqMessage.ToJsonString());
                        TestUtilitiesClass.SleepProducer();
                    }
                }
        }
Example #24
0
        public static void Create(int counter)
        {
            TestUtilitiesClass.PrintThreadId("TempQueueCreator.Create");
            ConnectionFactory connectionFactory = TestUtilitiesClass.GetConnectionFactory();
            IConnection       connection        = connectionFactory.CreateConnection();
            IModel            channel           = connection.CreateModel();
            string            queueName         = channel.QueueDeclare().QueueName;
            string            queueName2        = channel.QueueDeclare().QueueName;
            string            queueName3        = channel.QueueDeclare().QueueName;

            Console.WriteLine("Temp Queue Created: " + queueName);
            channel.ExchangeDeclare("tempExc", ExchangeType.Direct);
            channel.QueueBind(queueName, "tempExc", "routingKey1");
            channel.QueueBind(queueName2, "tempExc", "routingKey2");
            channel.QueueBind(queueName3, "tempExc", "routingKey1");
            for (int i = 0; i < counter; i++)
            {
                byte[]          message         = TestUtilitiesClass.GetMessage("TempQueueCreator");
                RabbitMqMessage rabbitMqMessage = TestUtilitiesClass.ParseMessage(message);
                channel.BasicPublish(exchange: "tempExc", routingKey: "routingKey1", basicProperties: null, body: message);
                Console.WriteLine("Sent {0}", rabbitMqMessage.ToJsonString());
            }
        }
Example #25
0
        public static void Main2(string[] args, int count)
        {
            ConnectionFactory factory = TestUtilitiesClass.GetConnectionFactory();

            using (IConnection connection = factory.CreateConnection())
                using (IModel channel = connection.CreateModel())
                {
                    channel.ExchangeDeclare(exchange: "topic_logs", type: ExchangeType.Topic);
                    string routingKey = (args.Length > 0) ? args[0] : "anonymous.info";
                    byte[] message    = (args.Length > 1)
                    ? TestUtilitiesClass.GetMessage(string.Join(" ", args.Skip(1).ToArray()))
                    : TestUtilitiesClass.GetMessage("Hello World!");
                    for (int i = 0; i < count; i++)
                    {
                        channel.BasicPublish(exchange: "topic_logs",
                                             routingKey: routingKey,
                                             basicProperties: null,
                                             body: message);
                        RabbitMqMessage rabbitMqMessage = TestUtilitiesClass.ParseMessage(message);
                        Console.WriteLine("[x] Sent '{0}':'{1}'", routingKey, rabbitMqMessage.ToJsonString());
                        TestUtilitiesClass.SleepProducer();
                    }
                }
        }
Example #26
0
        private void Consumer_RabbitReceived(RabbitMqMessage message, string consumer)
        {
            try
            {
                switch (message.Action)
                {
                case RabbitMqAction.Data:

                    Console.WriteLine("Articles Received");

                    HandleArticles(message.Data);

                    break;

                default:
                    Console.WriteLine("Unknown RabbitMQ Message.");
                    break;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Consumer_RabbitReceived: " + e.Message);
            }
        }
 public async Task Handle(RabbitMqMessage <int> message)
 {
     await _service.GenerateAsync(message.Payload);
 }
 public static RabbitMqCommandResult SubmitRabbitMqCommand(this ICommandDispatcher dispatcher, RabbitMqMessage <HelloWorldCommand> message)
 {
     return(dispatcher.Dispatch <RabbitMqMessage <HelloWorldCommand>, RabbitMqCommandResult>(message));
 }
 void AssertReceivedMessage(RabbitMqMessage <HelloWorldCommand> textMessage)
 {
     log.InfoFormat("Received a message with payload: {0}", textMessage.Payload);
     Assert.AreEqual("Hola!", textMessage.Payload.Input);
     messageReceived = true;
 }