コード例 #1
0
        public void MessageGoesToDispatcher()
        {
            EventMessageReceivedCallback callback = null;
            var receiverMock = new Mock <IMessageReceiver>(MockBehavior.Strict);

            receiverMock.Setup(r => r.StartReceivingMessages());
            receiverMock.Setup(r => r.StartHandlingMessages(It.IsAny <EventMessageReceivedCallback>()))
            .Callback <EventMessageReceivedCallback>(emrc => { callback = emrc; });

            var contextMock = new Mock <IBusContext <string> >(MockBehavior.Strict);

            contextMock.Setup(bc => bc.CreateMessageReceiver("My.Test.Queue", It.IsAny <IEnumerable <string> >()))
            .Returns(receiverMock.Object);

            var dispatcherMock = new Mock <IEventDispatcher>(MockBehavior.Strict);

            dispatcherMock.Setup(d => d.Dispatch(It.IsAny <EventMessage>()));
            var dispatchers = new Dictionary <string, IEventDispatcher>();

            dispatchers.Add("My.#", dispatcherMock.Object);

            var target = new EventListener <string>(contextMock.Object, dispatchers);

            target.StartListening("My.Test.Queue");

            // Act
            var message = new EventMessage {
                Topic = "My.Topic"
            };

            callback(message);

            // Assert
            dispatcherMock.Verify(d => d.Dispatch(message));
        }
コード例 #2
0
        public void StartReceivingMessages(EventMessageReceivedCallback callback)
        {
            CheckDisposed();
            if (_listening)
            {
                _log.LogWarning($"Trying to start listening to ({QueueName}) twice");
                throw new BusConfigurationException("Can't start listening multiple times");
            }
            if (callback == null)
            {
                throw new ArgumentNullException(nameof(callback));
            }

            var consumer = new AsyncEventingBasicConsumer(Channel);

            consumer.Received += async(model, ea) =>
            {
                var body    = ea.Body;
                var message = Encoding.UTF8.GetString(body);

                var eventMessage = new EventMessage(ea.RoutingKey, message, ea.BasicProperties.Type, ea.BasicProperties.Timestamp.UnixTime, ea.BasicProperties.CorrelationId);
                await Task.Run(() => callback(eventMessage));
            };

            Channel.BasicConsume(queue: QueueName,
                                 autoAck: true,
                                 consumerTag: "",
                                 noLocal: false,
                                 exclusive: false,
                                 arguments: null,
                                 consumer: consumer);
            _listening = true;
        }
コード例 #3
0
        /// <summary>
        /// Start consuming messages from the queue
        /// </summary>
        public virtual void StartHandlingMessages(EventMessageReceivedCallback callback)
        {
            if (!IsListening)
            {
                throw new BusConfigurationException("Receiver is not listening to events");
            }

            Consumer.Received += (model, args) =>
            {
                Logger.LogInformation($"Received event with id {args.BasicProperties.CorrelationId} " +
                                      $"of type {args.BasicProperties.Type} " +
                                      $"with topic {args.RoutingKey}");

                EventMessage eventMessage = new EventMessage
                {
                    Body          = args.Body,
                    Timestamp     = args.BasicProperties.Timestamp.UnixTime,
                    Topic         = args.RoutingKey,
                    EventType     = args.BasicProperties.Type,
                    CorrelationId = new Guid(args.BasicProperties.CorrelationId)
                };

                callback(eventMessage);
            };

            Logger.LogDebug($"Start consuming queue {QueueName}");
            Model.BasicConsume(QueueName, true, ConsumerTag, false, false, null, Consumer);
        }
コード例 #4
0
        public async Task AfterRemovingLastComsumer_PublishedMessageDoNotGoToConsumer()
        {
            // Arrange
            var target  = new MessageQueue(queueName, topicFilters);
            var message = new EventMessage {
                Topic = "MVM.SomeTopic"
            };
            EventMessage receivedMessage;
            EventMessageReceivedCallback callback = m => { receivedMessage = m; };

            target.SetConsumer(callback);

            // Check arrange
            receivedMessage = null;
            await target.PublishAsync(message);

            Assert.IsNotNull(receivedMessage);

            // Act
            target.RemoveConsumer(callback);

            // Assert
            receivedMessage = null;
            await target.PublishAsync(message);

            Assert.IsNull(receivedMessage);
        }
コード例 #5
0
 public void RemoveComsumer(string queueName, EventMessageReceivedCallback callback)
 {
     if (_queues.ContainsKey(queueName))
     {
         _queues[queueName].RemoveConsumer(callback);
     }
 }
コード例 #6
0
        public void StartReceivingMessages(EventMessageReceivedCallback callback)
        {
            if (_startedListening)
            {
                throw new BusConfigurationException("Cannot start receiving messages twice");
            }

            if (!Context.TestQueues.ContainsKey(QueueName))
            {
                throw new KeyNotFoundException("Queue " + QueueName + " does not exists");
            }

            new Task(() =>
            {
                var queue = Context.TestQueues[QueueName].Queue;

                while (true)
                {
                    if (queue.Count == 0)
                    {
                        Thread.Sleep(250);
                        continue;
                    }

                    callback.Invoke(queue.Dequeue());
                }
            }).Start();
            _startedListening = true;
        }
コード例 #7
0
        public void DisposeUnregistersCallback()
        {
            var queueName    = "My.QueueName";
            var topicFilters = new List <string> {
                "My.*.Filter", "MVM.#"
            };
            var context = new InMemoryContext();
            var target  = new InMemoryMessageReceiver(context, queueName, topicFilters);

            target.StartReceivingMessages();
            EventMessageReceivedCallback callback = m => { };

            target.StartHandlingMessages(callback);

            // Check Arrange
            var queue = context.Connection.GetNamedMessageQueue(queueName);

            Assert.AreEqual(true, queue.HasConsumer);

            // Act
            target.Dispose();

            // Assert
            queue = context.Connection.GetNamedMessageQueue(queueName);
            Assert.AreEqual(false, queue.HasConsumer);
        }
コード例 #8
0
        public void StartHandlingMessages(EventMessageReceivedCallback callback)
        {
            CanStartHandlingMessages();
            _hasStartHandlingMessages = true;

            _callback = callback;
            _messageBroker.BasicComsume(QueueName, callback);
        }
コード例 #9
0
        public void AfterSettingConsumer_MessageQueueHasConsumer()
        {
            var target = new MessageQueue(queueName, topicFilters);

            EventMessageReceivedCallback callback = m => { };

            target.SetConsumer(callback);

            Assert.AreEqual(true, target.HasConsumer);
        }
コード例 #10
0
 public void RemoveConsumer(EventMessageReceivedCallback callback)
 {
     lock (_messageQueue)
     {
         if (_consumer != null)
         {
             _consumer = null;
         }
     }
 }
コード例 #11
0
        private void CreateReceiver(EventMessageReceivedCallback handle, string queueName, List <string> expressions)
        {
            var messageReceiver = _context.CreateMessageReceiver(
                queueName: queueName,
                topicExpressions: expressions
                );

            messageReceiver.DeclareQueue();
            messageReceiver.StartReceivingMessages(handle);
        }
コード例 #12
0
        public InMemoryMessageReceiver(InMemoryContext inMemoryContext, string queueName, IEnumerable <string> topicExpressions)
        {
            _messageBroker = inMemoryContext.Connection;
            QueueName      = queueName;
            TopicFilters   = topicExpressions;

            _hasStartedReceivingMessages = false;
            _hasStartHandlingMessages    = false;
            _isDisposed = false;
            _callback   = null;
        }
コード例 #13
0
 public void BasicComsume(string queueName, EventMessageReceivedCallback callback)
 {
     try
     {
         _queues[queueName].SetConsumer(callback);
     }
     catch (KeyNotFoundException)
     {
         throw new BusConfigurationException($"Queue '{queueName}' has not been declared.");
     }
 }
コード例 #14
0
        public void BasicConsumeSetsConsumer()
        {
            var target = new MessageBroker();

            target.QueueDeclare(queueName, topicFilters);

            EventMessageReceivedCallback callback = m => { };

            target.BasicComsume(queueName, callback);

            Assert.IsTrue(target.GetNamedMessageQueue(queueName).HasConsumer);
        }
コード例 #15
0
        public void StartHandlingMessages_CreatesConsumer()
        {
            var target = new RabbitMQMessageReceiver(_busContext, _queueName, _topicFilters);

            target.StartReceivingMessages();

            // Act
            var callback = new EventMessageReceivedCallback(em => { });

            target.StartHandlingMessages(callback);

            Assert.IsNotNull(_consumer);
        }
コード例 #16
0
        public void MessageQueueHAsNoConsumersAfterRemovingLastComsumer()
        {
            var target = new MessageQueue(queueName, topicFilters);

            EventMessageReceivedCallback callback = m => { };

            target.SetConsumer(callback);
            Assert.AreEqual(true, target.HasConsumer);

            target.RemoveConsumer(callback);

            Assert.AreEqual(false, target.HasConsumer);
        }
コード例 #17
0
        public void StartHandlingMessages(EventMessageReceivedCallback Callback)
        {
            CanStartHandlingMessages();
            _hasStartHandlingMessages = true;

            var consumer = new EventingBasicConsumer(_channel);

            consumer.Received += (object sender, BasicDeliverEventArgs e) =>
            {
                var eventMesage = ConvertToEventMessage(e);
                Callback.Invoke(eventMesage);
            };
            _channel.BasicConsume(QueueName, autoAck: true, consumer);
        }
コード例 #18
0
        /// <summary>
        /// Create a new thread with an endless loop that waits for new
        /// messages in a specific queue
        /// </summary>
        public virtual void StartHandlingMessages(EventMessageReceivedCallback callback)
        {
            foreach (string topic in TopicFilters)
            {
                Logger.LogDebug($"Creating thread for queue {QueueName} with topic {topic}");

                Thread thread = new Thread(() => {
                    while (true)
                    {
                        // If the receiver is paused, keep it waiting
                        if (IsPaused)
                        {
                            Thread.Sleep(1000);
                            continue;
                        }

                        TestBusKey key = new TestBusKey(QueueName, topic);

                        Logger.LogTrace($"Waiting for message on queue {QueueName} with topic {topic}");

                        // Wait for messages
                        Context.DataQueues[key].AutoResetEvent.WaitOne();

                        // If the thread was paused while a message came in, reset the resetevent and continue
                        if (IsPaused)
                        {
                            Context.DataQueues[key].AutoResetEvent.Set();
                            continue;
                        }

                        Context.DataQueues[key].Queue.TryDequeue(out EventMessage result);

                        Logger.LogDebug($"Message received on queue {QueueName} with topic {topic}");

                        callback(result);
                    }
                });

                thread.IsBackground = true;
                thread.Start();
            }
        }
コード例 #19
0
        public void SetConsumer(EventMessageReceivedCallback callback)
        {
            lock (_messageQueue)
            {
                if (_consumer == null)
                {
                    _consumer = callback;

                    while (_messageQueue.Any())
                    {
                        EventMessage message = _messageQueue.Dequeue();
                        _consumer.Invoke(message);
                    }
                    return;
                }
                else
                {
                    throw new InvalidOperationException("Cannot subscribe a second listener to the same queue.");
                }
            }
        }