コード例 #1
0
        public void TestAtomicSendAndReceive()
        {
            var cachingConnectionFactory = new CachingConnectionFactory("localhost");
            var template = CreateSendAndReceiveRabbitTemplate(cachingConnectionFactory);

            template.DefaultSendDestination    = new RabbitDestination(string.Empty, ROUTE);
            template.DefaultReceiveDestination = new RabbitDestination(ROUTE);
            var task = Task.Run <IMessage>(() =>
            {
                IMessage message = null;
                for (var i = 0; i < 10; i++)
                {
                    message = template.Receive();
                    if (message != null)
                    {
                        break;
                    }

                    Thread.Sleep(100);
                }

                Assert.NotNull(message);
                template.Send(message.Headers.ReplyTo(), message);
                return(message);
            });
            var message = Message.Create(EncodingUtils.Utf8.GetBytes("test-message"), new MessageHeaders());
            var reply   = template.SendAndReceive(message);

            task.Wait(TimeSpan.FromSeconds(10));
            var received = task.Result;

            Assert.NotNull(received);
        }
コード例 #2
0
        public void TestTransactionalAndNonTransactionalChannelsSegregated()
        {
            var mockConnectionFactory = new Mock <ConnectionFactory>();
            var mockConnection        = new Mock <IConnection>();
            var mockChannel1          = new Mock <IModel>();
            var mockChannel2          = new Mock <IModel>();

            mockConnectionFactory.Setup(c => c.CreateConnection()).Returns(mockConnection.Object);
            mockConnection.Setup(c => c.CreateModel()).ReturnsInOrder(mockChannel1.Object, mockChannel2.Object);
            mockConnection.Setup(c => c.IsOpen).Returns(true);

            // Called during physical close
            mockChannel1.Setup(c => c.IsOpen).Returns(true);
            mockChannel2.Setup(c => c.IsOpen).Returns(true);

            var ccf = new CachingConnectionFactory(mockConnectionFactory.Object);

            ccf.ChannelCacheSize = 1;

            var con = ccf.CreateConnection();

            var channel1 = con.CreateChannel(true);

            channel1.TxSelect();
            channel1.Close(); // should be ignored, and add last into channel cache.

            /*
             * When a channel is created as non-transactional we should create a new one.
             */
            var channel2 = con.CreateChannel(false);

            channel2.Close(); // should be ignored, and add last into channel cache.
            Assert.AreNotSame(channel1, channel2);

            var ch1 = con.CreateChannel(true);  // remove first entry in cache (channel1)
            var ch2 = con.CreateChannel(false); // create new channel

            Assert.AreNotSame(ch1, ch2);
            Assert.AreSame(ch1, channel1); // The non-transactional one
            Assert.AreSame(ch2, channel2);

            ch1.Close();
            ch2.Close();

            mockConnection.Verify(c => c.CreateModel(), Times.Exactly(2));

            con.Close(); // should be ignored

            mockConnection.Verify(c => c.Close(), Times.Never());
            mockChannel1.Verify(c => c.Close(), Times.Never());
            mockChannel2.Verify(c => c.Close(), Times.Never());

            var notxlist = (LinkedList <IChannelProxy>)ReflectionUtils.GetInstanceFieldValue(ccf, "cachedChannelsNonTransactional");

            Assert.AreEqual(1, notxlist.Count);

            var txlist = (LinkedList <IChannelProxy>)ReflectionUtils.GetInstanceFieldValue(ccf, "cachedChannelsTransactional");

            Assert.AreEqual(1, txlist.Count);
        }
コード例 #3
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));
            }
        }
コード例 #4
0
        public void TestWithConnectionFactoryDefaults()
        {
            var mockConnectionFactory = new Mock <ConnectionFactory>();
            var mockConnection        = new Mock <IConnection>();
            var mockChannel           = new Mock <IModel>();

            mockConnectionFactory.Setup(factory => factory.CreateConnection()).Returns(mockConnection.Object);
            mockConnection.Setup(connection => connection.CreateModel()).Returns(mockChannel.Object);
            mockChannel.Setup(chan => chan.IsOpen).Returns(true);
            mockConnection.Setup(conn => conn.IsOpen).Returns(true);

            var ccf = new CachingConnectionFactory(mockConnectionFactory.Object);
            var con = ccf.CreateConnection();

            var channel = con.CreateChannel(false);

            channel.Close(); // should be ignored, and placed into channel cache.
            con.Close();     // should be ignored

            var con2 = ccf.CreateConnection();

            /*
             * will retrieve same channel object that was just put into channel cache
             */
            var channel2 = con2.CreateChannel(false);

            channel2.Close(); // should be ignored
            con2.Close();     // should be ignored

            Assert.AreSame(con, con2);
            Assert.AreSame(channel, channel2);
            mockConnection.Verify(conn => conn.Close(), Times.Never());
            mockChannel.Verify(chan => chan.Close(), Times.Never());
        }
コード例 #5
0
        public static void DisposeConnection_PropertyGet_IsFalse()
        {
            var factory        = new Mock <IDbConnectionFactory>();
            var cachingFactory = new CachingConnectionFactory(factory.Object);

            Assert.That(cachingFactory.DisposeConnection, Is.False);
        }
 public CachingConnectionFactoryIntegrationTests()
 {
     connectionFactory = new CachingConnectionFactory("localhost")
     {
         ServiceName = CF_INTEGRATION_CONNECTION_NAME
     };
 }
コード例 #7
0
        public void TestAvoidHangAMQP_508()
        {
            var cf       = new CachingConnectionFactory("localhost");
            var admin    = new RabbitAdmin(cf);
            var bytes    = new byte[300];
            var longName = Encoding.UTF8.GetString(bytes).Replace('\u0000', 'x');

            try
            {
                admin.DeclareQueue(new Queue(longName));
                throw new Exception("expected exception");
            }
            catch (Exception)
            {
                // Ignore
            }

            var goodName = "foobar";
            var name     = admin.DeclareQueue(new Queue(goodName));

            Assert.Null(admin.GetQueueProperties(longName));
            Assert.NotNull(admin.GetQueueProperties(goodName));
            admin.DeleteQueue(goodName);
            cf.Destroy();
        }
コード例 #8
0
        public void ReturnConnectionAfterCommit()
        {
            var txTemplate            = new TransactionTemplate(new TestTransactionManager());
            var mockConnectionFactory = new Mock <RC.IConnectionFactory>();
            var mockConnection        = new Mock <RC.IConnection>();
            var mockChannel           = new Mock <RC.IModel>();

            mockConnectionFactory.Setup((f) => f.CreateConnection(It.IsAny <string>())).Returns(mockConnection.Object);
            mockConnection.Setup((c) => c.IsOpen).Returns(true);
            mockConnection.Setup((c) => c.CreateModel()).Returns(mockChannel.Object);
            mockChannel.Setup((c) => c.IsOpen).Returns(true);
            mockChannel.Setup((c) => c.CreateBasicProperties()).Returns(new MockRabbitBasicProperties());

            var connectionFactory = new CachingConnectionFactory(mockConnectionFactory.Object);
            var template          = new RabbitTemplate(connectionFactory)
            {
                IsChannelTransacted = true
            };

            txTemplate.Execute(status =>
            {
                template.ConvertAndSend("foo", "bar");
            });
            txTemplate.Execute(status =>
            {
                template.ConvertAndSend("baz", "qux");
            });
            mockConnectionFactory.Verify((c) => c.CreateConnection(It.IsAny <string>()), Times.Once);
            mockConnection.Verify((c) => c.CreateModel(), Times.Once);
        }
コード例 #9
0
        public void TestRetry()
        {
            var connectionFactory = new Mock <RC.IConnectionFactory>();
            var connection        = new Mock <RC.IConnection>();

            connection.Setup(c => c.IsOpen).Returns(true);
            connectionFactory.Setup((f) => f.CreateConnection(It.IsAny <string>())).Returns(connection.Object);

            var channel1 = new Mock <RC.IModel>();

            channel1.Setup(c => c.IsOpen).Returns(true);
            connection.Setup(c => c.CreateModel()).Returns(channel1.Object);
            channel1.Setup((c) => c.QueueDeclare(It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <IDictionary <string, object> >())).Throws <Exception>();
            var ccf = new CachingConnectionFactory(connectionFactory.Object);

            var rtt = new PollyRetryTemplate(new Dictionary <Type, bool>(), 3, true, 1, 1, 1);
            var serviceCollection = CreateContainer();

            serviceCollection.AddSingleton <IConnectionFactory>(ccf);
            serviceCollection.AddRabbitAdmin((p, a) =>
            {
                a.RetryTemplate = rtt;
            });
            var foo = new Config.AnonymousQueue("foo");

            serviceCollection.AddRabbitQueue(foo);
            var provider = serviceCollection.BuildServiceProvider();
            var admin    = provider.GetRabbitAdmin();

            Assert.Throws <RabbitUncategorizedException>(() => ccf.CreateConnection());
            channel1.Verify((c) => c.QueueDeclare(It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <IDictionary <string, object> >()), Times.Exactly(3));
        }
コード例 #10
0
        public async Task TestDirect()
        {
            var cf        = new CachingConnectionFactory("localhost");
            var container = new DirectMessageListenerContainer(null, cf);

            container.SetQueueNames(Q1, Q2);
            container.ConsumersPerQueue = 2;
            var listener = new ReplyingMessageListener();
            var adapter  = new MessageListenerAdapter(null, listener);

            container.MessageListener     = adapter;
            container.ServiceName         = "simple";
            container.ConsumerTagStrategy = new TestConsumerTagStrategy(testName);
            await container.Start();

            Assert.True(container._startedLatch.Wait(TimeSpan.FromSeconds(10)));
            var template = new RabbitTemplate(cf);

            Assert.Equal("FOO", template.ConvertSendAndReceive <string>(Q1, "foo"));
            Assert.Equal("BAR", template.ConvertSendAndReceive <string>(Q2, "bar"));
            await container.Stop();

            Assert.True(await ConsumersOnQueue(Q1, 0));
            Assert.True(await ConsumersOnQueue(Q2, 0));
            Assert.True(await ActiveConsumerCount(container, 0));
            Assert.Empty(container._consumersByQueue);
            await template.Stop();

            cf.Destroy();
        }
コード例 #11
0
        public void MessageListenerTest()
        {
            var mockConnectionFactory = new Mock <RC.IConnectionFactory>();
            var mockConnection        = new Mock <RC.IConnection>();
            var onlyChannel           = new Mock <RC.IModel>();

            onlyChannel.Setup(m => m.IsOpen).Returns(true);

            var tooManyModels = new Exception();

            var cachingConnectionFactory = new CachingConnectionFactory(mockConnectionFactory.Object);

            mockConnectionFactory.Setup(m => m.CreateConnection()).Returns(mockConnection.Object);
            mockConnection.Setup(m => m.IsOpen).Returns(true);
            Func <RC.IModel> ensureOneModel = EnsureOneModel(onlyChannel.Object, tooManyModels);

            mockConnection.Setup(m => m.CreateModel()).Returns(onlyChannel.Object);

            RC.IBasicConsumer consumer;
            CountdownEvent    consumerLatch = new CountdownEvent(1);

            onlyChannel.Setup(m => m.BasicConsume(It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <bool>(), null, It.IsAny <RC.IBasicConsumer>()))
            .Returns((string queue, bool autoAck, string consumerTag, bool noLocal, bool exclusive, IDictionary <string, object> arguments, RC.IBasicConsumer iConsumer) =>
            {
                consumer = iConsumer;
                consumerLatch.Signal();
                return("consumerTag");
            });

            var commitLatch = new CountdownEvent(1);

            onlyChannel.Setup(m => m.TxCommit()).Callback(() =>
            {
                commitLatch.Signal();
            });

            var rollbackEvent = new CountdownEvent(1);

            onlyChannel.Setup(m => m.TxRollback()).Callback(() =>
            {
                rollbackEvent.Signal();
            });

            onlyChannel.Setup(m => m.BasicAck(It.IsAny <ulong>(), It.IsAny <bool>()));

            var latch     = new CountdownEvent(1);
            var container = new DirectMessageListenerContainer(null, cachingConnectionFactory);
            var adapter   = new MessageListenerAdapter(null, new TestListener(cachingConnectionFactory, latch));

            container.SetupMessageListener(adapter);

            container.SetQueueNames("queue");
            container.ShutdownTimeout      = 100;
            container.TransactionManager   = new DummyTxManager();
            container.TransactionAttribute = new DefaultTransactionAttribute();
            container.Initialize();
            container.Start();

            // Assert.True(consumerLatch.Wait(TimeSpan.FromSeconds(10)));
        }
コード例 #12
0
        public void TestAvoidHangAMQP_508()
        {
            var connectionFactory     = new CachingConnectionFactory("localhost");
            var longName              = new string('x', 300);
            var blockingQueueConsumer = new BlockingQueueConsumer(
                connectionFactory,
                new DefaultMessageHeadersConverter(),
                new ActiveObjectCounter <BlockingQueueConsumer>(),
                AcknowledgeMode.AUTO,
                true,
                1,
                null,
                longName,
                "foobar");

            try
            {
                blockingQueueConsumer.Start();
                throw new Exception("Expected exception");
            }
            catch (FatalListenerStartupException e)
            {
                Assert.IsType <R.Exceptions.WireFormattingException>(e.InnerException);
            }
            finally
            {
                connectionFactory.Destroy();
            }
        }
コード例 #13
0
 public void TestDoubleDeclarationOfExclusiveQueue()
 {
     // Expect exception because the queue is locked when it is declared a second time.
     var connectionFactory1 = new CachingConnectionFactory();
     connectionFactory1.Port = BrokerTestUtils.GetPort();
     var connectionFactory2 = new CachingConnectionFactory();
     connectionFactory2.Port = BrokerTestUtils.GetPort();
     var queue = new Queue("test.queue", false, true, true);
     this.rabbitAdmin.DeleteQueue(queue.Name);
     new RabbitAdmin(connectionFactory1).DeclareQueue(queue);
     try
     {
         new RabbitAdmin(connectionFactory2).DeclareQueue(queue);
         Assert.Fail("Expected an exception, and one was not thrown.");
     }
     catch (Exception ex)
     {
         Assert.True(ex is AmqpIOException, "Expecting an AmqpIOException");
     }
     finally
     {
         // Need to release the connection so the exclusive queue is deleted
         connectionFactory1.Dispose();
     }
 }
コード例 #14
0
        private void StockForm_Load(object sender, EventArgs e)
        {
            accountNameTextBox.Text          = DefaultAccountName;
            tradeQuantityNumericUpDown.Value = DefaultTradeRequestQuantity;
            txtRoutingKey.Text = DefaultRoutingKey;

            tradeOperationsGroupBox.Enabled = false;

            try
            {
                using (IConnectionFactory connectionFactory = new CachingConnectionFactory())
                {
                    IAmqpAdmin amqpAdmin = new RabbitAdmin(connectionFactory);

                    TopicExchange mktDataExchange = new TopicExchange("app.stock.marketdata", false, false);
                    amqpAdmin.DeclareExchange(mktDataExchange);
                    Spring.Messaging.Amqp.Core.Queue mktDataQueue = new Spring.Messaging.Amqp.Core.Queue("app.stock.marketdata");
                    amqpAdmin.DeclareQueue(mktDataQueue);

                    //Create the Exchange for MarketData Requests if it does not already exist.
                    //amqpAdmin.DeclareBinding(BindingBuilder.Bind(mktDataQueue).To(mktDataExchange).With(_currentBinding));
                    //Set up initial binding
                    RebindQueue(DefaultRoutingKey);
                }
            }
            catch (Exception ex)
            {
                log.ErrorFormat("Uncaught application exception.", ex);
            }
        }
コード例 #15
0
        public DirectReplyToMessageListenerContainerTest()
        {
            var adminCf = new CachingConnectionFactory("localhost");
            var admin   = new RabbitAdmin(adminCf);

            admin.DeclareQueue(new Config.Queue(TEST_RELEASE_CONSUMER_Q));
        }
コード例 #16
0
        public void TestTransactionalLowLevel()
        {
            var connectionFactory = new CachingConnectionFactory("localhost");
            var admin             = new RabbitAdmin(connectionFactory);

            admin.DeclareQueue(new Queue(QUEUE1_NAME));
            admin.DeclareQueue(new Queue(QUEUE2_NAME));
            var template = new RabbitTemplate(connectionFactory);
            var blockingQueueConsumer = new BlockingQueueConsumer(
                connectionFactory,
                new DefaultMessageHeadersConverter(),
                new ActiveObjectCounter <BlockingQueueConsumer>(),
                AcknowledgeMode.AUTO,
                true,
                1,
                null,
                QUEUE1_NAME,
                QUEUE2_NAME);
            var prefix = Guid.NewGuid().ToString();

            blockingQueueConsumer.TagStrategy = new TagStrategy(prefix);
            try
            {
                blockingQueueConsumer.Start();
                int n         = 0;
                var consumers = blockingQueueConsumer.CurrentConsumers();

                // Wait for consumers
                while (n < 100)
                {
                    if (consumers.Count < 2)
                    {
                        n++;
                        Thread.Sleep(100);
                        consumers = blockingQueueConsumer.CurrentConsumers();
                    }
                    else
                    {
                        break;
                    }
                }

                Assert.Equal(2, consumers.Count);
                var tags = new List <string>()
                {
                    consumers[0].ConsumerTag, consumers[1].ConsumerTag
                };
                Assert.Contains(prefix + "#" + QUEUE1_NAME, tags);
                Assert.Contains(prefix + "#" + QUEUE2_NAME, tags);
                blockingQueueConsumer.Stop();
                Assert.Null(template.ReceiveAndConvert <object>(QUEUE1_NAME));
            }
            finally
            {
                admin.DeleteQueue(QUEUE1_NAME);
                admin.DeleteQueue(QUEUE2_NAME);
                connectionFactory.Destroy();
            }
        }
        /// <summary>
        /// Creates the connection factory.
        /// </summary>
        /// <returns>The connection factory.</returns>
        protected virtual IConnectionFactory CreateConnectionFactory()
        {
            var connectionFactory = new CachingConnectionFactory();

            connectionFactory.ChannelCacheSize = this.concurrentConsumers;
            connectionFactory.Port             = BrokerTestUtils.GetPort();
            return(connectionFactory);
        }
コード例 #18
0
        public BatchingRabbitTemplateTest(ITestOutputHelper testOutputHelper)
        {
            connectionFactory = new CachingConnectionFactory("localhost");
            var admin = new RabbitAdmin(connectionFactory);

            admin.DeclareQueue(new Queue(ROUTE));
            this.testOutputHelper = testOutputHelper;
        }
コード例 #19
0
        public void Dispose()
        {
            var adminCf = new CachingConnectionFactory("localhost");
            var admin   = new RabbitAdmin(adminCf);

            admin.DeleteQueue(TEST_RELEASE_CONSUMER_Q);
            adminCf.Dispose();
        }
コード例 #20
0
        public void TestChannelCache()
        {
            var channelCf = new CachingConnectionFactory("localhost")
            {
                ServiceName      = "testChannelCache",
                ChannelCacheSize = 4
            };
            var c1 = channelCf.CreateConnection();
            var c2 = channelCf.CreateConnection();

            Assert.Same(c1, c2);
            var ch1 = c1.CreateChannel(false);
            var ch2 = c1.CreateChannel(false);
            var ch3 = c1.CreateChannel(true);
            var ch4 = c1.CreateChannel(true);
            var ch5 = c1.CreateChannel(true);

            ch1.Close();
            ch2.Close();
            ch3.Close();
            ch4.Close();
            ch5.Close();
            var props = channelCf.GetCacheProperties();

            Assert.StartsWith("testChannelCache", (string)props["connectionName"]);
            Assert.Equal(4, props["channelCacheSize"]);
            Assert.Equal(2, props["idleChannelsNotTx"]);
            Assert.Equal(3, props["idleChannelsTx"]);
            Assert.Equal(2, props["idleChannelsNotTxHighWater"]);
            Assert.Equal(3, props["idleChannelsTxHighWater"]);
            ch1   = c1.CreateChannel(false);
            ch3   = c1.CreateChannel(true);
            props = channelCf.GetCacheProperties();
            Assert.Equal(1, props["idleChannelsNotTx"]);
            Assert.Equal(2, props["idleChannelsTx"]);
            Assert.Equal(2, props["idleChannelsNotTxHighWater"]);
            Assert.Equal(3, props["idleChannelsTxHighWater"]);
            ch1 = c1.CreateChannel(false);
            ch2 = c1.CreateChannel(false);
            ch3 = c1.CreateChannel(true);
            ch4 = c1.CreateChannel(true);
            ch5 = c1.CreateChannel(true);
            var ch6 = c1.CreateChannel(true);
            var ch7 = c1.CreateChannel(true); // #5

            ch1.Close();
            ch2.Close();
            ch3.Close();
            ch4.Close();
            ch5.Close();
            ch6.Close();
            ch7.Close();
            props = channelCf.GetCacheProperties();
            Assert.Equal(2, props["idleChannelsNotTx"]);
            Assert.Equal(4, props["idleChannelsTx"]);
            Assert.Equal(2, props["idleChannelsNotTxHighWater"]);
            Assert.Equal(4, props["idleChannelsTxHighWater"]);
        }
コード例 #21
0
        public void TestCacheSizeExceeded()
        {
            var mockConnectionFactory = new Mock <ConnectionFactory>();
            var mockConnection        = new Mock <IConnection>();
            var mockChannel1          = new Mock <IModel>();
            var mockChannel2          = new Mock <IModel>();
            var mockChannel3          = new Mock <IModel>();

            mockConnectionFactory.Setup(c => c.CreateConnection()).Returns(mockConnection.Object);
            mockConnection.Setup(c => c.CreateModel()).ReturnsInOrder(mockChannel1.Object, mockChannel2.Object, mockChannel3.Object);
            mockConnection.Setup(c => c.IsOpen).Returns(true);

            // Called during physical close
            mockChannel1.Setup(c => c.IsOpen).Returns(true);
            mockChannel2.Setup(c => c.IsOpen).Returns(true);
            mockChannel3.Setup(c => c.IsOpen).Returns(true);

            var ccf = new CachingConnectionFactory(mockConnectionFactory.Object);

            ccf.ChannelCacheSize = 1;

            var con = ccf.CreateConnection();

            var channel1 = con.CreateChannel(false);

            // cache size is 1, but the other connection is not released yet so this creates a new one
            var channel2 = con.CreateChannel(false);

            Assert.AreNotSame(channel1, channel2);

            // should be ignored, and added last into channel cache.
            channel1.Close();

            // should be physically closed
            channel2.Close();

            // remove first entry in cache (channel1)
            var ch1 = con.CreateChannel(false);

            // create a new channel
            var ch2 = con.CreateChannel(false);

            Assert.AreNotSame(ch1, ch2);
            Assert.AreSame(ch1, channel1);
            Assert.AreNotSame(ch2, channel2);

            ch1.Close();
            ch2.Close();

            mockConnection.Verify(c => c.CreateModel(), Times.Exactly(3));

            con.Close(); // should be ignored

            mockConnection.Verify(c => c.Close(), Times.Never());
            mockChannel1.Verify(c => c.Close(), Times.Never());
            mockChannel2.Verify(c => c.Close(), Times.AtLeastOnce());
            mockChannel3.Verify(c => c.Close(), Times.AtLeastOnce());
        }
コード例 #22
0
        public void Create()
        {
            this.brokerIsRunning = BrokerRunning.IsRunningWithEmptyQueues(ROUTE);
            this.brokerIsRunning.Apply();
            var connectionFactory = new CachingConnectionFactory();

            connectionFactory.Port = BrokerTestUtils.GetPort();
            this.template          = new RabbitTemplate(connectionFactory);
        }
コード例 #23
0
 public DirectMessageListenerContainerIntegrationTest(ITestOutputHelper output)
 {
     adminCf = new CachingConnectionFactory("localhost");
     admin   = new RabbitAdmin(adminCf);
     admin.DeclareQueue(new Config.Queue(Q1));
     admin.DeclareQueue(new Config.Queue(Q2));
     testName = "DirectMessageListenerContainerIntegrationTest-" + testNumber++;
     _output  = output;
 }
コード例 #24
0
        public void DeclareQueue()
        {
            this.brokerIsRunning.Apply();
            var connectionFactory = new CachingConnectionFactory();

            connectionFactory.ChannelCacheSize = this.concurrentConsumers;
            connectionFactory.Port             = BrokerTestUtils.GetPort();
            this.template.ConnectionFactory    = connectionFactory;
        }
コード例 #25
0
        public async Task TestMasterLocator()
        {
            var factory = new RC.ConnectionFactory
            {
                Uri = new Uri("amqp://*****:*****@localhost:5672/")
            };
            var cf    = new CachingConnectionFactory(factory);
            var admin = new RabbitAdmin(cf);
            var queue = new AnonymousQueue();

            admin.DeclareQueue(queue);
            var client    = new HttpClient();
            var authToken = Encoding.ASCII.GetBytes("guest:guest");

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(authToken));

            var result = await client.GetAsync("http://localhost:15672/api/queues/%3F/" + queue.QueueName);

            var n = 0;

            while (n++ < 100 && result.StatusCode == HttpStatusCode.NotFound)
            {
                await Task.Delay(100);

                result = await client.GetAsync("http://localhost:15672/api/queues/%2F/" + queue.QueueName);
            }

            Assert.Equal(HttpStatusCode.OK, result.StatusCode);
            var content = await result.Content.ReadAsStringAsync();

            Assert.Contains("x-queue-master-locator", content);
            Assert.Contains("client-local", content);

            queue = new AnonymousQueue
            {
                MasterLocator = null
            };
            admin.DeclareQueue(queue);

            result = await client.GetAsync("http://localhost:15672/api/queues/%3F/" + queue.QueueName);

            n = 0;
            while (n++ < 100 && result.StatusCode == HttpStatusCode.NotFound)
            {
                await Task.Delay(100);

                result = await client.GetAsync("http://localhost:15672/api/queues/%2F/" + queue.QueueName);
            }

            Assert.Equal(HttpStatusCode.OK, result.StatusCode);
            content = await result.Content.ReadAsStringAsync();

            Assert.DoesNotContain("x-queue-master-locator", content);
            Assert.DoesNotContain("client-local", content);
            cf.Destroy();
        }
コード例 #26
0
        protected CachingConnectionFactory GetResource()
        {
            if (CachingConnectionFactory == null)
            {
                CachingConnectionFactory = new CachingConnectionFactory("localhost");
                CachingConnectionFactory.CreateConnection().Close();
            }

            return(CachingConnectionFactory);
        }
        public void CreateConnectionFactory()
        {
            this.brokerIsRunning = BrokerRunning.IsRunningWithEmptyQueues(this.queue);
            this.brokerIsRunning.Apply();
            var connectionFactory = new CachingConnectionFactory();

            connectionFactory.ChannelCacheSize = this.concurrentConsumers;
            connectionFactory.Port             = BrokerTestUtils.GetPort();
            this.template.ConnectionFactory    = connectionFactory;
        }
コード例 #28
0
        /// <summary>The apply.</summary>
        /// <returns>The System.Boolean.</returns>
        public bool Apply()
        {
            // Check at the beginning, so this can be used as a static field
            if (this.assumeOnline)
            {
                Assume.That(BrokerOnline.Get(this.port));
            }
            else
            {
                Assume.That(BrokerOffline.Get(this.port));
            }

            var connectionFactory = new CachingConnectionFactory();

            try
            {
                connectionFactory.Port = this.port;
                if (!string.IsNullOrWhiteSpace(this.hostName))
                {
                    connectionFactory.Host = this.hostName;
                }

                var admin    = new RabbitAdmin(connectionFactory);
                var exchange = new FederatedExchange("fedDirectRuleTest");
                exchange.BackingType = "direct";
                exchange.UpstreamSet = "upstream-set";
                admin.DeclareExchange(exchange);
                admin.DeleteExchange("fedDirectRuleTest");

                BrokerOffline.AddOrUpdate(this.port, false);

                if (!this.assumeOnline)
                {
                    Assume.That(BrokerOffline.Get(this.port));
                }
            }
            catch (Exception e)
            {
                Logger.Warn(m => m("Not executing tests because federated connectivity test failed"), e);
                BrokerOnline.AddOrUpdate(this.port, false);
                if (this.assumeOnline)
                {
                    Assume.That(e == null, "An exception occurred.");
                    return(false);
                }
            }
            finally
            {
                connectionFactory.Dispose();
            }

            return(true);

            // return super.apply(base, method, target);
        }
コード例 #29
0
        public void TestUninterruptibleListenerDMLC()
        {
            var cf    = new CachingConnectionFactory("localhost");
            var admin = new RabbitAdmin(cf);

            admin.DeclareQueue(new Config.Queue("test.shutdown"));

            var container = new DirectMessageListenerContainer(null, cf)
            {
                ShutdownTimeout = 500
            };

            container.SetQueueNames("test.shutdown");
            var latch     = new CountdownEvent(1);
            var testEnded = new CountdownEvent(1);
            var listener  = new TestListener(latch, testEnded);

            container.MessageListener = listener;
            var connection = cf.CreateConnection() as ChannelCachingConnectionProxy;

            // var channels = TestUtils.getPropertyValue(connection, "target.delegate._channelManager._channelMap");
            var field = typeof(RC.Framing.Impl.Connection)
                        .GetField("m_sessionManager", BindingFlags.Instance | BindingFlags.NonPublic);

            Assert.NotNull(field);
            var channels = (SessionManager)field.GetValue(connection.Target.Connection);

            Assert.NotNull(channels);

            container.Start();
            Assert.True(container._startedLatch.Wait(TimeSpan.FromSeconds(10)));

            try
            {
                var template = new RabbitTemplate(cf);
                template.Execute(c =>
                {
                    var properties = c.CreateBasicProperties();
                    var bytes      = EncodingUtils.GetDefaultEncoding().GetBytes("foo");
                    c.BasicPublish(string.Empty, "test.shutdown", false, properties, bytes);
                    RabbitUtils.SetPhysicalCloseRequired(c, false);
                });
                Assert.True(latch.Wait(TimeSpan.FromSeconds(30)));
                Assert.Equal(2, channels.Count);
            }
            finally
            {
                container.Stop();
                Assert.Equal(1, channels.Count);

                cf.Destroy();
                testEnded.Signal();
                admin.DeleteQueue("test.shutdown");
            }
        }
        public void ChannelReleasedOnTimeout()
        {
            var connectionFactory = new CachingConnectionFactory("localhost");
            var rabbitTemplate    = CreateSendAndReceiveRabbitTemplate(connectionFactory);

            rabbitTemplate.ReplyTimeout = 1;
            var exception = new AtomicReference <Exception>();
            var latch     = new CountdownEvent(1);

            rabbitTemplate.ReplyErrorHandler = new TestErrorHandler(exception, latch);
            var reply = rabbitTemplate.ConvertSendAndReceive <object>(ROUTE, "foo");

            Assert.Null(reply);
            var directReplyToContainers = rabbitTemplate._directReplyToContainers;
            var container = rabbitTemplate.UsePublisherConnection ? directReplyToContainers[connectionFactory.PublisherConnectionFactory] : directReplyToContainers[connectionFactory];

            Assert.Empty(container._inUseConsumerChannels);
            Assert.Same(rabbitTemplate.ReplyErrorHandler, container.ErrorHandler);
            var replyMessage = Message.Create(Encoding.UTF8.GetBytes("foo"), new MessageHeaders());

            var ex = Assert.Throws <RabbitRejectAndDontRequeueException>(() => rabbitTemplate.OnMessage(replyMessage));

            Assert.Contains("No correlation header in reply", ex.Message);

            var accessor = RabbitHeaderAccessor.GetMutableAccessor(replyMessage);

            accessor.CorrelationId = "foo";

            ex = Assert.Throws <RabbitRejectAndDontRequeueException>(() => rabbitTemplate.OnMessage(replyMessage));
            Assert.Contains("Reply received after timeout", ex.Message);

            _ = Task.Run(() =>
            {
                var message = rabbitTemplate.Receive(ROUTE, 10000);
                Assert.NotNull(message);
                rabbitTemplate.Send(message.Headers.ReplyTo(), replyMessage);
                return(message);
            });

            while (rabbitTemplate.Receive(ROUTE, 100) != null)
            {
            }

            reply = rabbitTemplate.ConvertSendAndReceive <object>(ROUTE, "foo");
            Assert.Null(reply);
            Assert.True(latch.Wait(TimeSpan.FromSeconds(10)));
            Assert.IsType <ListenerExecutionFailedException>(exception.Value);
            var listException = exception.Value as ListenerExecutionFailedException;

            Assert.Contains("Reply received after timeout", exception.Value.InnerException.Message);
            Assert.Equal(replyMessage.Payload, listException.FailedMessage.Payload);
            Assert.Empty(container._inUseConsumerChannels);
            rabbitTemplate.Stop().Wait();
            connectionFactory.Destroy();
        }