public void TestListenerRecoversFromClosedChannelAndStop()
        {
            var template = new RabbitTemplate(this.CreateConnectionFactory());

            var latch = new CountdownEvent(this.messageCount);

            this.container = this.CreateContainer(queue.Name, new AbortChannelListener(latch), this.CreateConnectionFactory());

            var n = 0;

            while (n++ < 100 && this.container.ActiveConsumerCount != this.concurrentConsumers)
            {
                Thread.Sleep(50);
            }

            Assert.AreEqual(this.concurrentConsumers, this.container.ActiveConsumerCount);

            for (var i = 0; i < this.messageCount; i++)
            {
                template.ConvertAndSend(queue.Name, i + "foo");
            }

            var timeout = this.GetTimeout();

            Logger.Debug("Waiting for messages with timeout = " + timeout + " (s)");
            var waited = latch.Wait(new TimeSpan(0, 0, timeout));

            Assert.True(waited, "Timed out waiting for message");

            Assert.Null(template.ReceiveAndConvert(queue.Name));

            Assert.AreEqual(this.concurrentConsumers, this.container.ActiveConsumerCount);
            this.container.Stop();
            Assert.AreEqual(0, this.container.ActiveConsumerCount);
        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            Tracer.Trace = new NLogAdapter();

            var brokerUri = "failover:(amqp://127.0.0.1:5672,amqp://127.0.0.1:5673)" +
                            "?failover.initialReconnectDelay=1000" +
                            "&failover.reconnectDelay=1000" +
                            "&failover.maxReconnectAttempts=10";
            var connectionFactory = new NmsConnectionFactory(brokerUri);
            var simpleMessageListenerContainer = new SimpleMessageListenerContainer
            {
                ConnectionFactory = connectionFactory,
                DestinationName   = DestinationName,
                MessageListener   = new MessageListener()
            };

            // start listener
            simpleMessageListenerContainer.AfterPropertiesSet();

            var cachingConnectionFactory = new CachingConnectionFactory(connectionFactory);
            var nmsTemplate = new NmsTemplate(cachingConnectionFactory)
            {
                DefaultDestinationName = DestinationName,
            };

            while (true)
            {
                Logger.Info("Enter your message.");
                var text = Console.ReadLine();
                nmsTemplate.SendWithDelegate(session => session.CreateTextMessage(text));
            }
        }
Exemplo n.º 3
0
        public void GatewayWithConnectionFactoryAndDestinationName()
        {
            XmlApplicationContext ctx =
                (XmlApplicationContext)
                NmsTestUtils.GetContext(@"Nms\Config\NmsGatewayWithConnectionFactoryAndDestinationName.xml");
            IPollableChannel         channel = (IPollableChannel)ctx.GetObject("requestChannel");
            NmsMessageDrivenEndpoint gateway = (NmsMessageDrivenEndpoint)ctx.GetObject("nmsGateway");

            Assert.That(gateway.GetType(), Is.EqualTo(typeof(NmsMessageDrivenEndpoint)));
            ctx.Start();

            ThreadPerTaskExecutor executor = new ThreadPerTaskExecutor();

            executor.Execute(delegate
            {
                SimpleMessageListenerContainer listenerContainer =
                    (SimpleMessageListenerContainer)
                    ctx.GetObject("Spring.Messaging.Nms.Listener.SimpleMessageListenerContainer#0");
                ISessionAwareMessageListener messageListener =
                    (ISessionAwareMessageListener)listenerContainer.MessageListener;
                messageListener.OnMessage(new StubTextMessage("message-driven-test"),
                                          new StubSession("message-driven-test"));
            });

            IMessage message = channel.Receive(TimeSpan.FromMilliseconds(3000));

            Assert.That(message, Is.Not.Null);
            Assert.That(message.Payload, Is.EqualTo("message-driven-test"));
            ctx.Stop();
        }
        private IMessageListener GetListener(string containerObjectName)
        {
            SimpleMessageListenerContainer container =
                (SimpleMessageListenerContainer)ctx.GetObject(containerObjectName);

            return((IMessageListener)container.MessageListener);
        }
        public void ContainerConfiguration()
        {
            var containers = ctx.GetObjects <SimpleMessageListenerContainer>();
            IConnectionFactory defaultConnectionFactory  = (IConnectionFactory)ctx.GetObject(DEFAULT_CONNECTION_FACTORY);
            IConnectionFactory explicitConnectionFactory = (IConnectionFactory)ctx.GetObject(EXPLICIT_CONNECTION_FACTORY);


            int defaultConnectionFactoryCount  = 0;
            int explicitConnectionFactoryCount = 0;

            foreach (KeyValuePair <string, SimpleMessageListenerContainer> dictionaryEntry in containers)
            {
                SimpleMessageListenerContainer container = dictionaryEntry.Value;
                if (container.ConnectionFactory.Equals(defaultConnectionFactory))
                {
                    defaultConnectionFactoryCount++;
                }
                else if (container.ConnectionFactory.Equals(explicitConnectionFactory))
                {
                    explicitConnectionFactoryCount++;
                }
            }

            Assert.AreEqual(1, defaultConnectionFactoryCount, "1 container should have the default connectionFactory");
            Assert.AreEqual(2, explicitConnectionFactoryCount, "2 containers should have the explicit connectionFactory");
        }
        static void Main(string[] args)
        {
            try
            {
                ConnectionFactory connectionFactory = new ConnectionFactory(URI);
                connectionFactory.UserName = USER;
                connectionFactory.Password = PASS;

                using (SimpleMessageListenerContainer listenerContainer = new SimpleMessageListenerContainer())
                {
                    listenerContainer.ConnectionFactory = connectionFactory;
                    listenerContainer.DestinationName   = DESTINATION;
                    listenerContainer.MessageListener   = new Listener();
                    listenerContainer.AfterPropertiesSet();
                    Console.WriteLine("Listener started.");
                    Console.WriteLine("Press <ENTER> to exit.");
                    Console.ReadLine();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Console.WriteLine("Press <ENTER> to exit.");
                Console.Read();
            }
            // comment when testing
            Console.ReadLine();
        }
        public void ContainerConfiguration()
        {
            IDictionary <string, object> containers = ctx.GetObjectsOfType(typeof(SimpleMessageListenerContainer));
            EmsConnectionFactory         defaultConnectionFactory = (EmsConnectionFactory)ctx.GetObject(DEFAULT_CONNECTION_FACTORY);

            defaultConnectionFactory = (EmsConnectionFactory)ctx.GetObject(DEFAULT_CONNECTION_FACTORY);
            EmsConnectionFactory explicitConnectionFactory = (EmsConnectionFactory)ctx.GetObject(EXPLICIT_CONNECTION_FACTORY);


            int defaultConnectionFactoryCount  = 0;
            int explicitConnectionFactoryCount = 0;

            foreach (KeyValuePair <string, object> dictionaryEntry in containers)
            {
                SimpleMessageListenerContainer container = (SimpleMessageListenerContainer)dictionaryEntry.Value;
                if (container.ConnectionFactory.Equals(defaultConnectionFactory))
                {
                    defaultConnectionFactoryCount++;
                }
                else if (container.ConnectionFactory.Equals(explicitConnectionFactory))
                {
                    explicitConnectionFactoryCount++;
                    Assert.AreEqual(4, container.ConcurrentConsumers);
                }
            }

            Assert.AreEqual(1, defaultConnectionFactoryCount, "1 container should have the default connectionFactory");
            Assert.AreEqual(2, explicitConnectionFactoryCount, "2 containers should have the explicit connectionFactory");
        }
        public void TestListenerSendsMessageAndThenRollback()
        {
            var connectionFactory = this.CreateConnectionFactory();
            var template          = new RabbitTemplate(connectionFactory);

            new RabbitAdmin(connectionFactory).DeclareQueue(sendQueue);

            this.acknowledgeMode = AcknowledgeModeUtils.AcknowledgeMode.Auto;
            this.transactional   = true;

            var latch = new CountdownEvent(1);

            this.container = this.CreateContainer(queue.Name, new ChannelSenderListener(sendQueue.Name, latch, true), connectionFactory);
            template.ConvertAndSend(queue.Name, "foo");

            var timeout = this.GetTimeout();

            Logger.Debug("Waiting for messages with timeout = " + timeout + " (s)");
            var waited = latch.Wait(timeout * 1000);

            Assert.True(waited, "Timed out waiting for message");

            this.container.Stop();
            Thread.Sleep(200);

            // Foo message is redelivered
            Assert.AreEqual("foo", template.ReceiveAndConvert(queue.Name));

            // Sending of bar message is also rolled back
            Assert.Null(template.ReceiveAndConvert(sendQueue.Name));
        }
        public void TestListenerSendsMessageAndThenContainerCommits()
        {
            var connectionFactory = this.CreateConnectionFactory();
            var template          = new RabbitTemplate(connectionFactory);

            new RabbitAdmin(connectionFactory).DeclareQueue(sendQueue);

            this.acknowledgeMode = AcknowledgeModeUtils.AcknowledgeMode.Auto;
            this.transactional   = true;

            var latch = new CountdownEvent(1);

            this.container = this.CreateContainer(queue.Name, new ChannelSenderListener(sendQueue.Name, latch, false), connectionFactory);
            template.ConvertAndSend(queue.Name, "foo");

            var timeout = this.GetTimeout();

            Logger.Debug("Waiting for messages with timeout = " + timeout + " (s)");
            var waited = latch.Wait(new TimeSpan(0, 0, timeout));

            Assert.True(waited, "Timed out waiting for message");

            Thread.Sleep(500);

            // All messages committed
            var bytes = (byte[])template.ReceiveAndConvert(sendQueue.Name);

            Assert.NotNull(bytes);
            Assert.AreEqual("bar", Encoding.UTF8.GetString(bytes));
            Assert.AreEqual(null, template.ReceiveAndConvert(queue.Name));
        }
Exemplo n.º 10
0
        public void TestDefaultConsumerCount()
        {
            var container = new SimpleMessageListenerContainer(new SingleConnectionFactory());

            container.MessageListener = new MessageListenerAdapter(this);
            container.QueueNames      = new[] { "foo" };
            container.AutoStartup     = false;
            container.AfterPropertiesSet();
            Assert.AreEqual(1, ReflectionUtils.GetInstanceFieldValue(container, "concurrentConsumers"));
        }
Exemplo n.º 11
0
        private ReservationWorker()
        {
            ConnectionFactory factory = new ConnectionFactory(Config.Url);

            listenerContainer = new SimpleMessageListenerContainer
            {
                ConnectionFactory = factory,
                DestinationName   = Config.ReturnMessageQueue,
                MessageListener   = new GenericMessageListener <MessageDto>(new MessageHandler())
            };
            listenerContainer.AfterPropertiesSet();
        }
Exemplo n.º 12
0
        /// <summary>Does the test.</summary>
        /// <param name="concurrentConsumers">The concurrent consumers.</param>
        /// <param name="configurer">The configurer.</param>
        private void DoTest(int concurrentConsumers, IContainerConfigurer configurer)
        {
            var messageCount      = 10;
            var template          = new RabbitTemplate();
            var connectionFactory = new CachingConnectionFactory();

            connectionFactory.ChannelCacheSize = concurrentConsumers;
            connectionFactory.Port             = BrokerTestUtils.GetPort();
            template.ConnectionFactory         = connectionFactory;
            var messageConverter = new SimpleMessageConverter();

            messageConverter.CreateMessageIds = true;
            template.MessageConverter         = messageConverter;
            for (var i = 0; i < messageCount; i++)
            {
                template.ConvertAndSend(queue1.Name, i);
                template.ConvertAndSend(queue2.Name, i);
            }

            var container = new SimpleMessageListenerContainer(connectionFactory);
            var latch     = new CountdownEvent(messageCount * 2);
            var listener  = new MultiplePocoListener(latch);

            container.MessageListener     = new MessageListenerAdapter(listener);
            container.AcknowledgeMode     = AcknowledgeModeUtils.AcknowledgeMode.Auto;
            container.ChannelTransacted   = true;
            container.ConcurrentConsumers = concurrentConsumers;
            configurer.Configure(container);
            container.AfterPropertiesSet();
            container.Start();
            try
            {
                var timeout = Math.Min((1 + messageCount) / concurrentConsumers, 50);
                Logger.Info("Timeout: " + timeout);
                var waited = latch.Wait(timeout * 1000);
                Logger.Info("All messages recovered: " + waited);
                Assert.AreEqual(concurrentConsumers, container.ActiveConsumerCount);
                Assert.True(waited, "Timed out waiting for messages");
            }
            catch (ThreadInterruptedException e)
            {
                Thread.CurrentThread.Interrupt();
                throw new ThreadStateException("unexpected interruption");
            }
            finally
            {
                container.Shutdown();
                Assert.AreEqual(0, container.ActiveConsumerCount);
            }

            Assert.Null(template.ReceiveAndConvert(queue1.Name));
            Assert.Null(template.ReceiveAndConvert(queue2.Name));
        }
        /// <summary>Creates the container.</summary>
        /// <param name="queueName">Name of the queue.</param>
        /// <param name="listener">The listener.</param>
        /// <param name="connectionFactory">The connection factory.</param>
        /// <returns>The container.</returns>
        private SimpleMessageListenerContainer CreateContainer(string queueName, object listener, IConnectionFactory connectionFactory)
        {
            var container = new SimpleMessageListenerContainer(connectionFactory);

            container.MessageListener     = new MessageListenerAdapter(listener);
            container.QueueNames          = new[] { queueName };
            container.ConcurrentConsumers = this.concurrentConsumers;
            container.ChannelTransacted   = this.transactional;
            container.AcknowledgeMode     = this.acknowledgeMode;
            container.AfterPropertiesSet();
            container.Start();
            return(container);
        }
Exemplo n.º 14
0
        /// <summary>Does the sunny day test.</summary>
        /// <param name="latch">The latch.</param>
        /// <param name="listener">The listener.</param>
        private void DoSunnyDayTest(CountdownEvent latch, object listener)
        {
            this.container = this.CreateContainer(listener);
            for (var i = 0; i < this.messageCount; i++)
            {
                this.template.ConvertAndSend(this.queue.Name, i + "foo");
            }

            Logger.Debug(m => m("Waiting {0} seconds for messages to be received.", Math.Max(2, this.messageCount / 20)));
            var waited = latch.Wait(new TimeSpan(0, 0, 0, Math.Max(2, this.messageCount / 20)));

            Assert.True(waited, "Timed out waiting for message");
            Assert.Null(this.template.ReceiveAndConvert(this.queue.Name));
        }
 public void TestListenerDoesNotRecoverFromMissingQueue()
 {
     try
     {
         this.concurrentConsumers = 3;
         var latch = new CountdownEvent(this.messageCount);
         this.container = this.CreateContainer("nonexistent", new VanillaListener(latch), this.CreateConnectionFactory());
     }
     catch (Exception e)
     {
         Assert.True(e is AmqpIllegalStateException);
         this.concurrentConsumers = 1;
     }
 }
        private SimpleMessageListenerContainer CreateContainer(object listener)
        {
            var container = new SimpleMessageListenerContainer(this.template.ConnectionFactory);

            container.MessageListener     = new MessageListenerAdapter(listener);
            container.QueueNames          = new[] { this.queue.Name };
            container.TxSize              = this.txSize;
            container.PrefetchCount       = this.txSize;
            container.ConcurrentConsumers = this.concurrentConsumers;
            container.ChannelTransacted   = this.transactional;
            container.AcknowledgeMode     = AcknowledgeModeUtils.AcknowledgeMode.Auto;
            container.AfterPropertiesSet();
            container.Start();
            return(container);
        }
Exemplo n.º 17
0
        public void TestListenerRecoversFromDeadBroker()
        {
            var queues = this.brokerAdmin.GetQueues();

            Logger.Info("Queues: " + queues);
            Assert.AreEqual(1, queues.Count);
            Assert.True(queues[0].Durable);

            var template = new RabbitTemplate(this.connectionFactory);

            var latch = new CountdownEvent(this.messageCount);

            Assert.AreEqual(this.messageCount, latch.CurrentCount, "No more messages to receive before even sent!");
            this.container = this.CreateContainer(this.queue.Name, new VanillaListener(latch), this.connectionFactory);
            for (var i = 0; i < this.messageCount; i++)
            {
                template.ConvertAndSend(this.queue.Name, i + "foo");
            }

            Assert.True(latch.CurrentCount > 0, "No more messages to receive before broker stopped");
            Logger.Info(string.Format("Latch.CurrentCount Before Shutdown: {0}", latch.CurrentCount));
            this.brokerAdmin.StopBrokerApplication();
            Assert.True(latch.CurrentCount > 0, "No more messages to receive after broker stopped");
            Logger.Info(string.Format("Latch.CurrentCount After Shutdown: {0}", latch.CurrentCount));
            var waited = latch.Wait(500);

            Assert.False(waited, "Did not time out waiting for message");

            this.container.Stop();
            Assert.AreEqual(0, this.container.ActiveConsumerCount);
            Logger.Info(string.Format("Latch.CurrentCount After Container Stop: {0}", latch.CurrentCount));
            this.brokerAdmin.StartBrokerApplication();
            queues = this.brokerAdmin.GetQueues();
            Logger.Info("Queues: " + queues);
            this.container.Start();
            Logger.Info(string.Format("Concurrent Consumers After Container Start: {0}", this.container.ActiveConsumerCount));
            Assert.AreEqual(this.concurrentConsumers, this.container.ActiveConsumerCount);
            Logger.Info(string.Format("Latch.CurrentCount After Container Start: {0}", latch.CurrentCount));
            var timeout = Math.Min((4 + this.messageCount) / (4 * this.concurrentConsumers), 30);

            Logger.Debug("Waiting for messages with timeout = " + timeout + " (s)");
            waited = latch.Wait(timeout * 1000);
            Assert.True(waited, "Timed out waiting for message");

            Assert.IsNull(template.ReceiveAndConvert(this.queue.Name));
        }
 public void TestSingleListenerDoesNotRecoverFromMissingQueue()
 {
     try
     {
         /*
          * A single listener sometimes doesn't have time to attempt to start before we ask it if it has failed, so this
          * is a good test of that potential bug.
          */
         this.concurrentConsumers = 1;
         var latch = new CountdownEvent(this.messageCount);
         this.container = this.CreateContainer("nonexistent", new VanillaListener(latch), this.CreateConnectionFactory());
     }
     catch (Exception e)
     {
         Assert.True(e is AmqpIllegalStateException);
     }
 }
        public void Clear()
        {
            // Wait for broker communication to finish before trying to stop container
            Thread.Sleep(300);
            Logger.Debug("Shutting down at end of test");
            if (this.container != null)
            {
                this.container.Shutdown();
            }

            if (this.container != null)
            {
                this.container.Dispose();
            }

            this.container = null;
        }
Exemplo n.º 20
0
        public void TestInconsistentAcknowledgeConfiguration()
        {
            var container = new SimpleMessageListenerContainer(new SingleConnectionFactory());

            container.MessageListener   = new MessageListenerAdapter(this);
            container.QueueNames        = new[] { "foo" };
            container.ChannelTransacted = true;
            container.AcknowledgeMode   = AcknowledgeModeUtils.AcknowledgeMode.None;

            try
            {
                container.AfterPropertiesSet();
            }
            catch (Exception e)
            {
                Assert.True(e is InvalidOperationException);
            }
        }
Exemplo n.º 21
0
        public void TestListenerWithManualAckNonTransactional()
        {
            var latch = new CountdownEvent(this.messageCount);

            this.container = this.CreateContainer(new TestListener(latch));
            for (var i = 0; i < this.messageCount; i++)
            {
                this.template.ConvertAndSend(queue.Name, i + "foo");
            }

            var timeout = Math.Min(1 + this.messageCount / (4 * this.concurrentConsumers), 30);

            Logger.Debug("Waiting for messages with timeout = " + timeout + " (s)");
            var waited = latch.Wait(timeout * 1000);

            Assert.True(waited, "Timed out waiting for message");
            Assert.Null(this.template.ReceiveAndConvert(queue.Name));
        }
        public void TestListenerTransactionalFails()
        {
            this.transactional = true;
            var latch = new CountdownEvent(this.messageCount);

            this.container = this.CreateContainer(new TxTestListener(latch, true, this));
            for (var i = 0; i < this.txSize; i++)
            {
                this.template.ConvertAndSend(this.queue.Name, i + "foo");
            }

            var timeout = Math.Min(1 + (this.messageCount / (4 * this.concurrentConsumers)), 30);

            Logger.Debug("Waiting for messages with timeout = " + timeout + " (s)");
            var waited = latch.Wait(new TimeSpan(0, 0, 0, timeout));

            Assert.True(waited, "Timed out waiting for message");
            Assert.Null(this.template.ReceiveAndConvert(this.queue.Name));
        }
Exemplo n.º 23
0
        /// <summary>Does the listener with exception test.</summary>
        /// <param name="latch">The latch.</param>
        /// <param name="listener">The listener.</param>
        private void DoListenerWithExceptionTest(CountdownEvent latch, object listener)
        {
            this.container = this.CreateContainer(listener);
            if (this.acknowledgeMode.TransactionAllowed())
            {
                // Should only need one message if it is going to fail
                for (var i = 0; i < this.concurrentConsumers; i++)
                {
                    this.template.ConvertAndSend(this.queue.Name, i + "foo");
                }
            }
            else
            {
                for (var i = 0; i < this.messageCount; i++)
                {
                    this.template.ConvertAndSend(this.queue.Name, i + "foo");
                }
            }

            try
            {
                Logger.Debug(m => m("Waiting {0} seconds for messages to be received.", 5 + Math.Max(1, this.messageCount / 10)));
                var waited = latch.Wait(new TimeSpan(0, 0, 0, 5 + Math.Max(1, this.messageCount / 10)));
                Assert.True(waited, "Timed out waiting for message");
            }
            finally
            {
                // Wait for broker communication to finish before trying to stop
                // container
                Thread.Sleep(300);
                this.container.Shutdown();
                Thread.Sleep(300);
            }

            if (this.acknowledgeMode.TransactionAllowed())
            {
                Assert.NotNull(this.template.ReceiveAndConvert(this.queue.Name));
            }
            else
            {
                Assert.Null(this.template.ReceiveAndConvert(this.queue.Name));
            }
        }
Exemplo n.º 24
0
        /// <summary>Creates the container.</summary>
        /// <param name="listener">The listener.</param>
        /// <returns>The container.</returns>
        private SimpleMessageListenerContainer CreateContainer(object listener)
        {
            var container = new SimpleMessageListenerContainer(this.template.ConnectionFactory);

            container.MessageListener     = listener;
            container.QueueNames          = new[] { this.queue.Name };
            container.TxSize              = this.txSize;
            container.PrefetchCount       = this.txSize;
            container.ConcurrentConsumers = this.concurrentConsumers;
            container.ChannelTransacted   = this.transactional;
            container.AcknowledgeMode     = this.acknowledgeMode;
            if (this.externalTransaction)
            {
                container.TransactionManager = new IntegrationTestTransactionManager();
            }

            container.AfterPropertiesSet();
            container.Start();
            return(container);
        }
Exemplo n.º 25
0
        /// <summary>Does the test.</summary>
        /// <param name="messageCount">The message count.</param>
        /// <param name="errorHandler">The error handler.</param>
        /// <param name="latch">The latch.</param>
        /// <param name="listener">The listener.</param>
        public void DoTest(int messageCount, IErrorHandler errorHandler, CountdownEvent latch, object listener)
        {
            var concurrentConsumers = 1;
            var template            = this.CreateTemplate(concurrentConsumers);

            // Send messages to the queue
            for (var i = 0; i < messageCount; i++)
            {
                template.ConvertAndSend(queue.Name, i + "foo");
            }

            var container = new SimpleMessageListenerContainer(template.ConnectionFactory);

            container.MessageListener     = listener;
            container.AcknowledgeMode     = AcknowledgeModeUtils.AcknowledgeMode.None;
            container.ChannelTransacted   = false;
            container.ConcurrentConsumers = concurrentConsumers;

            container.PrefetchCount = messageCount;
            container.TxSize        = messageCount;
            container.QueueNames    = new[] { queue.Name };
            container.ErrorHandler  = errorHandler;
            container.AfterPropertiesSet();
            container.Start();

            var waited = latch.Wait(1000);

            if (messageCount > 1)
            {
                Assert.True(waited, "Expected to receive all messages before stop");
            }

            try
            {
                Assert.Null(template.ReceiveAndConvert(queue.Name));
            }
            finally
            {
                container.Shutdown();
            }
        }
Exemplo n.º 26
0
        public void SendAndAsyncReceive()
        {
            SimpleMessageListenerContainer container =
                (SimpleMessageListenerContainer)applicationContext["SimpleMessageListenerContainer"];
            SimpleMessageListener listener = applicationContext["SimpleMessageListener"] as SimpleMessageListener;

            Assert.IsNotNull(container);
            Assert.IsNotNull(listener);

            Admin admin = new Admin("tcp://localhost:7222", "admin", null);

            admin.PurgeQueue("test.queue");

            EmsTemplate emsTemplate = (EmsTemplate)applicationContext["MessageTemplate"] as EmsTemplate;

            Assert.IsNotNull(emsTemplate);

            Assert.AreEqual(0, listener.MessageCount);
            emsTemplate.ConvertAndSend("Hello World 1");

            int waitInMillis = 2000;

            Thread.Sleep(waitInMillis);
            Assert.AreEqual(1, listener.MessageCount);

            container.Stop();
            Console.WriteLine("container stopped.");
            emsTemplate.ConvertAndSend("Hello World 2");
            Thread.Sleep(waitInMillis);
            Assert.AreEqual(1, listener.MessageCount);

            container.Start();
            Console.WriteLine("container started.");
            Thread.Sleep(waitInMillis);
            Assert.AreEqual(2, listener.MessageCount);

            container.Shutdown();

            Thread.Sleep(waitInMillis);
        }
        public void TestListenerRecoversFromClosedConnection()
        {
            var template = new RabbitTemplate(this.CreateConnectionFactory());

            var latch             = new CountdownEvent(this.messageCount);
            var connectionFactory = this.CreateConnectionFactory();

            this.container = this.CreateContainer(queue.Name, new CloseConnectionListener((IConnectionProxy)connectionFactory.CreateConnection(), latch), connectionFactory);
            for (var i = 0; i < this.messageCount; i++)
            {
                template.ConvertAndSend(queue.Name, i + "foo");
            }

            var timeout = Math.Min(4 + (this.messageCount / (4 * this.concurrentConsumers)), 30);

            Logger.Debug("Waiting for messages with timeout = " + timeout + " (s)");
            var waited = latch.Wait(new TimeSpan(0, 0, timeout));

            Assert.True(waited, "Timed out waiting for message");

            Assert.Null(template.ReceiveAndConvert(queue.Name));
        }
        public void TestListenerRecoversFromBogusDoubleAck()
        {
            var template = new RabbitTemplate(this.CreateConnectionFactory());

            this.acknowledgeMode = AcknowledgeModeUtils.AcknowledgeMode.Manual;

            var latch = new CountdownEvent(this.messageCount);

            this.container = this.CreateContainer(queue.Name, new ManualAckListener(latch), this.CreateConnectionFactory());
            for (var i = 0; i < this.messageCount; i++)
            {
                template.ConvertAndSend(queue.Name, i + "foo");
            }

            var timeout = this.GetTimeout();

            Logger.Debug("Waiting for messages with timeout = " + timeout + " (s)");
            var waited = latch.Wait(new TimeSpan(0, 0, timeout));

            Assert.True(waited, "Timed out waiting for message");

            Assert.Null(template.ReceiveAndConvert(queue.Name));
        }
Exemplo n.º 29
0
        protected void listen(IMessageEventHandler <T> handler, string url, string queueName)
        {
            try
            {
                ConnectionFactory factory = new ConnectionFactory(url);

                SimpleMessageListenerContainer listenerContainer = new SimpleMessageListenerContainer();
                listenerContainer.ConnectionFactory = factory;
                listenerContainer.DestinationName   = queueName;
                listenerContainer.MessageListener   = new GenericMessageListener <T>(handler);
                listenerContainer.AfterPropertiesSet();

                string info = String.Format("Service started!");
                writeToLog(info, LogMessage.LogType.INFO);
                Console.WriteLine(info);
                Console.WriteLine("Press ENTER to exit.");
                Console.ReadLine();
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
        public void SendAndAsyncReceive()
        {
            SimpleMessageListenerContainer container =
                (SimpleMessageListenerContainer)applicationContext["SimpleMessageListenerContainer"];
            SimpleMessageListener listener = applicationContext["SimpleMessageListener"] as SimpleMessageListener;

            Assert.IsNotNull(container);
            Assert.IsNotNull(listener);


            NmsTemplate nmsTemplate = (NmsTemplate)applicationContext["MessageTemplate"] as NmsTemplate;

            Assert.IsNotNull(nmsTemplate);

            Assert.AreEqual(0, listener.MessageCount);
            nmsTemplate.ConvertAndSend("Hello World 1");

            int waitInMillis = 2000;

            Thread.Sleep(waitInMillis);
            Assert.AreEqual(1, listener.MessageCount);

            container.Stop();
            Console.WriteLine("container stopped.");
            nmsTemplate.ConvertAndSend("Hello World 2");
            Thread.Sleep(waitInMillis);
            Assert.AreEqual(1, listener.MessageCount);

            container.Start();
            Console.WriteLine("container started.");
            Thread.Sleep(waitInMillis);
            Assert.AreEqual(2, listener.MessageCount);

            container.Shutdown();

            Thread.Sleep(waitInMillis);
        }