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();
            }
        }
Example #2
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;
 }
Example #3
0
        public void TestMixTransactionalAndNonTransactional()
        {
            var template1 = new RabbitTemplate(this.connectionFactory);
            var template2 = new RabbitTemplate(this.connectionFactory);

            template1.ChannelTransacted = true;

            var admin = new RabbitAdmin(this.connectionFactory);
            var queue = admin.DeclareQueue();

            template1.ConvertAndSend(queue.Name, "message");

            var result = (string)template2.ReceiveAndConvert(queue.Name);

            Assert.AreEqual("message", result);

            try
            {
                template2.Execute <object>(
                    delegate(IModel channel)
                {
                    // Should be an exception because the channel is not transactional
                    channel.TxRollback();
                    return(null);
                });
            }
            catch (Exception ex)
            {
                Assert.True(ex is AmqpIOException, "The channel is not transactional.");
            }
        }
        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);
            }
        }
Example #5
0
        public DirectReplyToMessageListenerContainerTest()
        {
            var adminCf = new CachingConnectionFactory("localhost");
            var admin   = new RabbitAdmin(adminCf);

            admin.DeclareQueue(new Config.Queue(TEST_RELEASE_CONSUMER_Q));
        }
Example #6
0
        public static void Configure()
        {
            using (IConnectionFactory connectionFactory = new CachingConnectionFactory())
            {
                IAmqpAdmin amqpAdmin = new RabbitAdmin(connectionFactory);

                //Each queue is automatically bound to the default direct exchange.
                amqpAdmin.DeclareQueue(new Queue(ConfigurationManager.AppSettings["STOCK_REQUEST_QUEUE_NAME"]));
                amqpAdmin.DeclareQueue(new Queue(ConfigurationManager.AppSettings["STOCK_RESPONSE_QUEUE_NAME"]));

                //handled by the java server app on startup
                //TopicExchange mktDataExchange = new TopicExchange(ConfigurationManager.AppSettings["MARKET_DATA_EXCHANGE_NAME"], false, false);
                //amqpAdmin.DeclareExchange(mktDataExchange);

                var mktDataQueue = new Queue(ConfigurationManager.AppSettings["MARKET_DATA_QUEUE_NAME"]);
                amqpAdmin.DeclareQueue(mktDataQueue);
            }
        }
        public void TestSendAndReceiveFromVolatileQueueAfterImplicitRemoval()
        {
            var template = new RabbitTemplate(connectionFactory);
            var admin    = new RabbitAdmin(connectionFactory);
            var queue    = admin.DeclareQueue();

            template.ConvertAndSend(queue.QueueName, "message");
            connectionFactory.ResetConnection();
            Assert.Throws <RabbitIOException>(() => template.ReceiveAndConvert <string>(queue.QueueName));
        }
Example #8
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 TestSendAndReceiveFromVolatileQueue()
        {
            var template = new RabbitTemplate(connectionFactory);
            var admin    = new RabbitAdmin(connectionFactory);
            var queue    = admin.DeclareQueue();

            template.ConvertAndSend(queue.QueueName, "message");
            var result = template.ReceiveAndConvert <string>(queue.QueueName);

            Assert.Equal("message", result);
        }
Example #10
0
        static void Main(string[] args)
        {
            using (IConnectionFactory connectionFactory = new CachingConnectionFactory())
            {
                IAmqpAdmin amqpAdmin = new RabbitAdmin(connectionFactory);

                //Each queue is automatically bound to the default direct exchange.
                amqpAdmin.DeclareQueue(new Queue(ConfigurationManager.AppSettings["STOCK_REQUEST_QUEUE_NAME"]));
                amqpAdmin.DeclareQueue(new Queue(ConfigurationManager.AppSettings["STOCK_RESPONSE_QUEUE_NAME"]));

                TopicExchange mktDataExchange = new TopicExchange(ConfigurationManager.AppSettings["MARKET_DATA_EXCHANGE_NAME"], false, false);
                amqpAdmin.DeclareExchange(mktDataExchange);
                Queue mktDataQueue = new Queue(ConfigurationManager.AppSettings["MARKET_DATA_QUEUE_NAME"]);
                amqpAdmin.DeclareQueue(mktDataQueue);

                Console.WriteLine("Queues and exchanges have been declared.");
                Console.WriteLine("Press 'enter' to exit");
                Console.ReadLine();
            }
        }
Example #11
0
            public CustomStartupFixture()
            {
                adminCf = new CachingConnectionFactory("localhost");
                admin   = new RabbitAdmin(adminCf, null);
                foreach (var q in Queues)
                {
                    var queue = new Config.Queue(q);
                    admin.DeclareQueue(queue);
                }

                services = CreateContainer();
                Provider = services.BuildServiceProvider();
                Provider.GetRequiredService <IHostedService>().StartAsync(default).Wait();
Example #12
0
        public void TestHardErrorAndReconnect()
        {
            var template = new RabbitTemplate(this.connectionFactory);
            var admin    = new RabbitAdmin(this.connectionFactory);
            var queue    = new Queue("foo");

            admin.DeclareQueue(queue);
            var route = queue.Name;

            var latch = new CountdownEvent(1);

            try
            {
                template.Execute <object>(
                    (IModel channel) =>
                {
                    ((IChannelProxy)channel).GetConnection().ConnectionShutdown += delegate
                    {
                        Logger.Info("Error");
                        if (latch.CurrentCount > 0)
                        {
                            latch.Signal();
                        }

                        // This will be thrown on the Connection thread just before it dies, so basically ignored
                        throw new SystemException();
                    };

                    var internalTag = channel.BasicConsume(route, false, new DefaultBasicConsumer(channel));

                    // Consume twice with the same tag is a hard error (connection will be reset)
                    var internalResult = channel.BasicConsume(route, false, internalTag, new DefaultBasicConsumer(channel));
                    Assert.Fail("Expected IOException, got: " + internalResult);
                    return(null);
                });

                Assert.Fail("Expected AmqpIOException");
            }
            catch (AmqpIOException e)
            {
                // expected
            }

            template.ConvertAndSend(route, "message");
            Assert.True(latch.Wait(1000));
            var result = (string)template.ReceiveAndConvert(route);

            Assert.AreEqual("message", result);
            result = (string)template.ReceiveAndConvert(route);
            Assert.AreEqual(null, result);
        }
Example #13
0
        private static void Main(string[] args)
        {
            using (IConnectionFactory connectionFactory = new CachingConnectionFactory())
            {
                IAmqpAdmin amqpAdmin = new RabbitAdmin(connectionFactory);

                var helloWorldQueue = new Queue("hello.world.queue");

                amqpAdmin.DeclareQueue(helloWorldQueue);

                //Each queue is automatically bound to the default direct exchange.

                Console.WriteLine("Queue [hello.world.queue] has been declared.");
                Console.WriteLine("Press 'enter' to exit");
                Console.ReadLine();
            }
        }
Example #14
0
        static void Main(string[] args)
        {
            var connectionFactory = new CachingConnectionFactory()
            {
                Host = "localhost"
            };
            var admin = new RabbitAdmin(connectionFactory);

            admin.DeclareQueue(new Queue("myqueue"));
            var template = new RabbitTemplate(connectionFactory);

            template.ConvertAndSend("myqueue", "foo");
            var foo = template.ReceiveAndConvert <string>("myqueue");

            admin.DeleteQueue("myQueue");
            connectionFactory.Dispose();
            Console.WriteLine(foo);
        }
        public void TestArgumentsQueue()
        {
            var queue = this.objectFactory.GetObject <Queue>("arguments");

            Assert.IsNotNull(queue);

            var template    = new RabbitTemplate(new CachingConnectionFactory(BrokerTestUtils.GetPort()));
            var rabbitAdmin = new RabbitAdmin(template.ConnectionFactory);

            rabbitAdmin.DeleteQueue(queue.Name);
            rabbitAdmin.DeclareQueue(queue);

            Assert.AreEqual(100L, queue.Arguments["x-message-ttl"]);
            template.ConvertAndSend(queue.Name, "message");

            Thread.Sleep(200);
            var result = (string)template.ReceiveAndConvert(queue.Name);

            Assert.AreEqual(null, result);
        }
        public void TestMixTransactionalAndNonTransactional()
        {
            var template1 = new RabbitTemplate(connectionFactory);
            var template2 = new RabbitTemplate(connectionFactory);

            template1.IsChannelTransacted = true;

            var admin = new RabbitAdmin(connectionFactory);
            var queue = admin.DeclareQueue();

            template1.ConvertAndSend(queue.QueueName, "message");
            var result = template2.ReceiveAndConvert <string>(queue.QueueName);

            Assert.Equal("message", result);

            Assert.Throws <RabbitIOException>(() => template2.Execute <object>((c) =>
            {
                c.TxRollback();
                return(null);
            }));
        }
Example #17
0
        public void TestSendAndReceiveFromVolatileQueueAfterImplicitRemoval()
        {
            var template = new RabbitTemplate(this.connectionFactory);

            var admin = new RabbitAdmin(this.connectionFactory);
            var queue = admin.DeclareQueue();

            template.ConvertAndSend(queue.Name, "message");

            // Force a physical close of the channel
            this.connectionFactory.Dispose();

            try
            {
                var result = (string)template.ReceiveAndConvert(queue.Name);
                Assert.AreEqual("message", result);
            }
            catch (Exception e)
            {
                Assert.True(e is AmqpIOException);
            }
        }
Example #18
0
        public void TestHardErrorAndReconnectNoAuto()
        {
            var template = new RabbitTemplate(connectionFactory);
            var admin    = new RabbitAdmin(connectionFactory);
            var queue    = new Config.Queue(CF_INTEGRATION_TEST_QUEUE);

            admin.DeclareQueue(queue);
            var route = queue.QueueName;
            var latch = new CountdownEvent(1);

            try
            {
                template.Execute((channel) =>
                {
                    channel.ModelShutdown += (sender, args) =>
                    {
                        latch.Signal();
                        throw new ShutdownSignalException(args);
                    };
                    var tag    = RC.IModelExensions.BasicConsume(channel, route, false, new RC.DefaultBasicConsumer(channel));
                    var result = RC.IModelExensions.BasicConsume(channel, route, false, tag, new RC.DefaultBasicConsumer(channel));
                    throw new Exception("Expected Exception, got: " + result);
                });
                throw new Exception("Expected AmqpIOException");
            }
            catch (RabbitIOException)
            {
            }

            template.ConvertAndSend(route, "message");
            Assert.True(latch.Wait(TimeSpan.FromSeconds(10)));
            var result = template.ReceiveAndConvert <string>(route);

            Assert.Equal("message", result);
            result = template.ReceiveAndConvert <string>(route);
            Assert.Null(result);
            admin.DeleteQueue(CF_INTEGRATION_TEST_QUEUE);
        }
        public void TestFailOnFirstUseWithMissingBroker()
        {
            var connectionFactory = new SingleConnectionFactory("foo");

            connectionFactory.Port = 434343;
            var applicationContext = new GenericApplicationContext();

            applicationContext.ObjectFactory.RegisterSingleton("foo", new Queue("queue"));
            var rabbitAdmin = new RabbitAdmin(connectionFactory);

            rabbitAdmin.ApplicationContext = applicationContext;
            rabbitAdmin.AutoStartup        = true;
            rabbitAdmin.AfterPropertiesSet();

            try
            {
                rabbitAdmin.DeclareQueue();
            }
            catch (Exception ex)
            {
                Assert.True(ex is AmqpIOException, "Expecting an AmqpIOException");
            }
        }
Example #20
0
        public void SurviveAReconnect()
        {
            var myQueue = new Config.Queue("my-queue");
            var cf      = new RC.ConnectionFactory
            {
                Uri = new Uri("amqp://localhost")
            };

            var ccf = new CachingConnectionFactory(cf)
            {
                ChannelCacheSize       = 2,
                ChannelCheckoutTimeout = 2000
            };
            var admin = new RabbitAdmin(ccf);

            admin.DeclareQueue(myQueue);
            var template = new RabbitTemplate(ccf);

            CheckIt(template, 0, myQueue.ActualName);

            var i = 1;

            while (i < 45)
            {
                // While in this loop, stop and start the broker
                // The CCF should reconnect and the receives in
                // Checkit should stop throwing exceptions
                // The available permits should always be == 2.
                Thread.Sleep(2000);
                CheckIt(template, i++, myQueue.ActualName);
                var values = ccf._checkoutPermits.Values.GetEnumerator();
                values.MoveNext();
                var availablePermits = values.Current.CurrentCount;
                output.WriteLine("Permits after test: " + availablePermits);
                Assert.Equal(2, availablePermits);
            }
        }
Example #21
0
        private void StockForm_Load(object sender, EventArgs e)
        {
            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("APP.STOCK.QUOTES.nasdaq.*");
                }
            }
            catch (Exception ex)
            {
                log.ErrorFormat("Uncaught application exception.", ex);
            }
        }
        /// <summary>
        /// Applies this instance.
        /// </summary>
        /// <returns>Something here.</returns>
        public bool Apply()
        {
            // Check at the beginning, so this can be used as a static field
            if (this.assumeOnline)
            {
                Assume.That(brokerOnline[this.port]);
            }
            else
            {
                Assume.That(brokerOffline[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);

                foreach (var queue in this.queues)
                {
                    var queueName = queue.Name;

                    if (this.purge)
                    {
                        Logger.Debug("Deleting queue: " + queueName);

                        // Delete completely - gets rid of consumers and bindings as well
                        try
                        {
                            admin.DeleteQueue(queueName);
                        }
                        catch (Exception ex)
                        {
                            Logger.Warn("Could not delete queue. Assuming it didn't exist.", ex);
                        }
                    }

                    if (this.IsDefaultQueue(queueName))
                    {
                        // Just for test probe.
                        try
                        {
                            admin.DeleteQueue(queueName);
                        }
                        catch (Exception ex)
                        {
                            Logger.Warn("Could not delete queue. Assuming it didn't exist.", ex);
                        }
                    }
                    else
                    {
                        admin.DeclareQueue(queue);
                    }
                }

                brokerOffline.AddOrUpdate(this.port, false);

                if (!this.assumeOnline)
                {
                    Assume.That(brokerOffline[this.port]);
                }
            }
            catch (Exception e)
            {
                Logger.Warn("Not executing tests because basic connectivity test failed", e);

                brokerOnline.AddOrUpdate(this.port, false);

                if (this.assumeOnline)
                {
                    return(false);

                    // Assume.That(!(e is Exception));
                }
            }
            finally
            {
                connectionFactory.Dispose();
            }

            return(true);

            // return base.Apply(base, method, target);
        }