/// <summary>
        /// Declares a queue whose name is automatically named by the server.  It is created with
        /// exclusive = true, autoDelete=true, and durable = false.
        /// </summary>
        /// <returns>The queue.</returns>
        public Queue DeclareQueue()
        {
            var queueName = this.rabbitTemplate.Execute(channel => channel.QueueDeclare());
            var queue     = new Queue(queueName.QueueName, false, true, true);

            return(queue);
        }
        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);
            }
        }
Beispiel #3
0
        private void RebindQueue(string routingKey)
        {
            var ctx     = ContextRegistry.GetContext();
            var factory =
                ctx.GetObject("ConnectionFactory") as IConnectionFactory;

            try
            {
                IAmqpAdmin amqpAdmin = new RabbitAdmin(factory);

                TopicExchange mktDataExchange = new TopicExchange("APP.STOCK.MARKETDATA", false, false);
                Spring.Messaging.Amqp.Core.Queue mktDataQueue = new Spring.Messaging.Amqp.Core.Queue("APP.STOCK.MARKETDATA");

                if (!string.IsNullOrEmpty(_currentBinding))
                {
                    amqpAdmin.RemoveBinding(BindingBuilder.Bind(mktDataQueue).To(mktDataExchange).With(_currentBinding));
                }

                _currentBinding = routingKey;
                if (!string.IsNullOrEmpty(_currentBinding))
                {
                    amqpAdmin.DeclareBinding(BindingBuilder.Bind(mktDataQueue).To(mktDataExchange).With(_currentBinding));
                    txtRoutingKey.Text = _currentBinding;
                }
            }
            catch (Exception ex)
            {
                log.ErrorFormat("Uncaught application exception.", ex);
            }
        }
 /// <summary>Declares the queue.</summary>
 /// <param name="queue">The queue.</param>
 public void DeclareQueue(Queue queue)
 {
     this.rabbitTemplate.Execute <object>(
         channel =>
     {
         this.DeclareQueues(channel, queue);
         return(null);
     });
 }
Beispiel #5
0
        private static void Main(string[] args)
        {
            using (IConnectionFactory connectionFactory = new SingleConnectionFactory())
            {
                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();
            }
        }
        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);
            }
        }
Beispiel #7
0
        static void Main(string[] args)
        {
            using (IConnectionFactory connectionFactory = new SingleConnectionFactory())
            {
                IAmqpAdmin amqpAdmin = new RabbitAdmin(connectionFactory);

                var marketDataQueue = new Queue("APP.STOCK.MARKETDATA");
                amqpAdmin.DeclareQueue(marketDataQueue);

                amqpAdmin.DeclareQueue(new Queue("APP.STOCK.REQUEST"));
                amqpAdmin.DeclareQueue(new Queue("APP.STOCK.JOE"));

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

                Console.WriteLine("Queues and exchanges have been declared.");
                Console.WriteLine("Press 'enter' to exit");
                Console.ReadLine();
            }
        }
        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();
            }
        }
        public void TestReplyToOneDeep()
        {
            var mockConnectionFactory = new Mock<ConnectionFactory>();
            var mockConnection = new Mock<IConnection>();
            var mockChannel = new Mock<IModel>();

            mockConnectionFactory.Setup(m => m.CreateConnection()).Returns(mockConnection.Object);
            mockConnection.Setup(m => m.IsOpen).Returns(true);
            mockConnection.Setup(m => m.CreateModel()).Returns(mockChannel.Object);
            mockChannel.Setup(m => m.CreateBasicProperties()).Returns(() => new BasicProperties());

            var template = new RabbitTemplate(new SingleConnectionFactory(mockConnectionFactory.Object));
            var replyQueue = new Queue("new.replyTo");
            template.ReplyQueue = replyQueue;

            var messageProperties = new MessageProperties();
            messageProperties.ReplyTo = "replyTo1";
            var message = new Message(Encoding.UTF8.GetBytes("Hello, world!"), messageProperties);
            var props = new List<IBasicProperties>();
            mockChannel.Setup(m => m.BasicPublish(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<bool>(), It.IsAny<IBasicProperties>(), It.IsAny<byte[]>())).Callback<string, string, bool, bool, IBasicProperties, byte[]>(
                (a1, a2, a3, a4, a5, a6) =>
                {
                    var basicProps = a5;
                    props.Add(basicProps);
                    var springProps = new DefaultMessagePropertiesConverter().ToMessageProperties(basicProps, null, "UTF-8");
                    var replyMessage = new Message(Encoding.UTF8.GetBytes("!dlrow olleH"), springProps);
                    template.OnMessage(replyMessage);
                });

            var reply = template.SendAndReceive(message);
            Assert.IsNotNull(reply);

            Assert.AreEqual(1, props.Count);
            var basicProperties = props[0];
            Assert.AreEqual("new.replyTo", basicProperties.ReplyTo);
            Assert.AreEqual("replyTo1", basicProperties.Headers[RabbitTemplate.STACKED_REPLY_TO_HEADER]);
            Assert.IsNotNull(basicProperties.Headers[RabbitTemplate.STACKED_CORRELATION_HEADER]);
        }
Beispiel #10
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);
            }
        }
        public void TestStartupWithLazyDeclaration()
        {
            var queue = new Queue("test.queue");
            this.context.ObjectFactory.RegisterSingleton("foo", queue);
            this.rabbitAdmin.AfterPropertiesSet();

            // A new connection is initialized so the queue is declared
            Assert.True(this.rabbitAdmin.DeleteQueue(queue.Name));
        }
 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);
     }
     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();
     }
 }
        public void TestSpringWithDefaultExchangeImplicitBinding()
        {
            var exchange = new DirectExchange(RabbitAdmin.DEFAULT_EXCHANGE_NAME);
            this.context.ObjectFactory.RegisterSingleton("foo", exchange);
            var queueName = "test.queue";
            var queue = new Queue(queueName, false, false, false);
            this.context.ObjectFactory.RegisterSingleton("bar", queue);
            var binding = new Binding(queueName, Binding.DestinationType.Queue, exchange.Name, queueName, null);
            this.context.ObjectFactory.RegisterSingleton("baz", binding);
            this.rabbitAdmin.AfterPropertiesSet();

            this.rabbitAdmin.Initialize();

            // Pass by virtue of RabbitMQ not firing a 403 reply code for both exchange and binding declaration
            Assert.True(this.QueueExists(queue));
        }
        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);
            }
        }
 /// <summary>Declares the queue.</summary>
 /// <param name="queue">The queue.</param>
 public void DeclareQueue(Queue queue)
 {
     this.rabbitTemplate.Execute<object>(
         channel =>
         {
             this.DeclareQueues(channel, queue);
             return null;
         });
 }
 /// <summary>
 /// Declares a queue whose name is automatically named by the server.  It is created with
 /// exclusive = true, autoDelete=true, and durable = false.
 /// </summary>
 /// <returns>The queue.</returns>
 public Queue DeclareQueue()
 {
     var queueName = this.rabbitTemplate.Execute(channel => channel.QueueDeclare());
     var queue = new Queue(queueName.QueueName, false, true, true);
     return queue;
 }
        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);
        }
 public RoutingKeyConfigurer(Queue queue, IExchange exchange)
 {
     this.queue = queue;
     this.exchange = exchange;
 }
        public void TestReplyToThreeDeep()
        {
            var mockConnectionFactory = new Mock<ConnectionFactory>();
            var mockConnection = new Mock<IConnection>();
            var mockChannel = new Mock<IModel>();

            mockConnectionFactory.Setup(m => m.CreateConnection()).Returns(mockConnection.Object);
            mockConnection.Setup(m => m.IsOpen).Returns(true);
            mockConnection.Setup(m => m.CreateModel()).Returns(mockChannel.Object);
            mockChannel.Setup(m => m.CreateBasicProperties()).Returns(() => new BasicProperties());

            var template = new RabbitTemplate(new SingleConnectionFactory(mockConnectionFactory.Object));
            var replyQueue = new Queue("new.replyTo");
            template.ReplyQueue = replyQueue;

            var messageProperties = new MessageProperties();
            messageProperties.ReplyTo = "replyTo2";
            messageProperties.SetHeader(RabbitTemplate.STACKED_REPLY_TO_HEADER, "replyTo1");
            messageProperties.SetHeader(RabbitTemplate.STACKED_CORRELATION_HEADER, "a");
            var message = new Message(Encoding.UTF8.GetBytes("Hello, world!"), messageProperties);
            var props = new List<IBasicProperties>();

            var count = new AtomicInteger();
            var nestedReplyTo = new List<string>();
            var nestedReplyStack = new List<string>();
            var nestedCorrelation = new List<string>();

            mockChannel.Setup(m => m.BasicPublish(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<bool>(), It.IsAny<IBasicProperties>(), It.IsAny<byte[]>())).Callback<string, string, bool, bool, IBasicProperties, byte[]>
                (
                    (a1, a2, a3, a4, a5, a6) =>
                    {
                        var basicProps = a5;
                        props.Add(basicProps);
                        var springProps = new DefaultMessagePropertiesConverter().ToMessageProperties(basicProps, null, "UTF-8");
                        var replyMessage = new Message(Encoding.UTF8.GetBytes("!dlrow olleH"), springProps);
                        if (count.IncrementValueAndReturn() < 2)
                        {
                            var anotherMessage = new Message(Encoding.UTF8.GetBytes("Second"), springProps);
                            replyMessage = template.SendAndReceive(anotherMessage);
                            nestedReplyTo.Add(replyMessage.MessageProperties.ReplyTo);
                            nestedReplyStack.Add((string)replyMessage.MessageProperties.Headers[RabbitTemplate.STACKED_REPLY_TO_HEADER]);
                            nestedCorrelation.Add((string)replyMessage.MessageProperties.Headers[RabbitTemplate.STACKED_CORRELATION_HEADER]);
                        }

                        template.OnMessage(replyMessage);
                    });

            var reply = template.SendAndReceive(message);
            Assert.IsNotNull(reply);

            Assert.AreEqual(2, props.Count);
            var basicProperties = props[0];
            Assert.AreEqual("new.replyTo", basicProperties.ReplyTo);
            Assert.AreEqual("replyTo2:replyTo1", basicProperties.Headers[RabbitTemplate.STACKED_REPLY_TO_HEADER]);
            Assert.IsTrue(((string)basicProperties.Headers[RabbitTemplate.STACKED_CORRELATION_HEADER]).EndsWith(":a"));

            basicProperties = props[1];
            Assert.AreEqual("new.replyTo", basicProperties.ReplyTo);
            Assert.AreEqual("new.replyTo:replyTo2:replyTo1", basicProperties.Headers[RabbitTemplate.STACKED_REPLY_TO_HEADER]);
            Assert.IsTrue(((string)basicProperties.Headers[RabbitTemplate.STACKED_CORRELATION_HEADER]).EndsWith(":a"));

            Assert.AreEqual("replyTo1", reply.MessageProperties.Headers[RabbitTemplate.STACKED_REPLY_TO_HEADER]);
            Assert.AreEqual("a", reply.MessageProperties.Headers[RabbitTemplate.STACKED_CORRELATION_HEADER]);

            Assert.AreEqual(1, nestedReplyTo.Count);
            Assert.AreEqual(1, nestedReplyStack.Count);
            Assert.AreEqual(1, nestedCorrelation.Count);
            Assert.AreEqual("replyTo2:replyTo1", nestedReplyStack[0]);
            Assert.IsTrue(nestedCorrelation[0].EndsWith(":a"));
        }
        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);
            }
        }
        private void RebindQueue(string routingKey)
        {
            var ctx = ContextRegistry.GetContext();
            var factory =
                ctx.GetObject("ConnectionFactory") as IConnectionFactory;

            try
            {
                IAmqpAdmin amqpAdmin = new RabbitAdmin(factory);

                TopicExchange mktDataExchange = new TopicExchange("APP.STOCK.MARKETDATA", false, false);
                Spring.Messaging.Amqp.Core.Queue mktDataQueue = new Spring.Messaging.Amqp.Core.Queue("APP.STOCK.MARKETDATA");

                if (!string.IsNullOrEmpty(_currentBinding))
                    amqpAdmin.RemoveBinding(BindingBuilder.Bind(mktDataQueue).To(mktDataExchange).With(_currentBinding));

                _currentBinding = routingKey;
                if (!string.IsNullOrEmpty(_currentBinding))
                {
                    amqpAdmin.DeclareBinding(BindingBuilder.Bind(mktDataQueue).To(mktDataExchange).With(_currentBinding));
                    txtRoutingKey.Text = _currentBinding;
                }

            }
            catch (Exception ex)
            {
                log.ErrorFormat("Uncaught application exception.", ex);
            }
        }
        public void TestSpringWithDefaultExchangeNonImplicitBinding()
        {
            var exchange = new DirectExchange(RabbitAdmin.DEFAULT_EXCHANGE_NAME);
            this.context.ObjectFactory.RegisterSingleton("foo", exchange);
            var queueName = "test.queue";
            var queue = new Queue(queueName, false, false, false);
            this.context.ObjectFactory.RegisterSingleton("bar", queue);
            var binding = new Binding(queueName, Binding.DestinationType.Queue, exchange.Name, "test.routingKey", null);
            this.context.ObjectFactory.RegisterSingleton("baz", binding);
            this.rabbitAdmin.AfterPropertiesSet();

            try
            {
                this.rabbitAdmin.DeclareBinding(binding);
            }
            catch (AmqpIOException ex)
            {
                Exception cause = ex;
                Exception rootCause = null;
                while (cause != null)
                {
                    rootCause = cause;
                    cause = cause.InnerException;
                }

                Assert.True(rootCause.Message.Contains("code=403"));
                Assert.True(rootCause.Message.Contains("operation not permitted on the default exchange"));
            }
        }
        public void TestRemoveBindingWithDefaultExchangeImplicitBinding()
        {
            var queueName = "test.queue";
            var queue = new Queue(queueName, false, false, false);
            this.rabbitAdmin.DeclareQueue(queue);
            var binding = new Binding(queueName, Binding.DestinationType.Queue, RabbitAdmin.DEFAULT_EXCHANGE_NAME, queueName, null);

            this.rabbitAdmin.RemoveBinding(binding);

            // Pass by virtue of RabbitMQ not firing a 403 reply code
        }
        public void TestStartupWithNonDurable()
        {
            var queue = new Queue("test.queue", false, false, false);
            this.context.ObjectFactory.RegisterSingleton("foo", queue);
            this.rabbitAdmin.AfterPropertiesSet();

            var connectionHolder = new AtomicReference<IConnection>();

            var rabbitTemplate = new RabbitTemplate(this.connectionFactory);

            // Force RabbitAdmin to initialize the queue
            var exists = rabbitTemplate.Execute<bool>(delegate(IModel channel)
            {
                var result = channel.QueueDeclarePassive(queue.Name);
                connectionHolder.LazySet(((CachedModel)channel).Connection);
                return result != null;
            });
            Assert.True(exists, "Expected Queue to exist");

            Assert.True(this.QueueExists(connectionHolder.Value, queue));

            // simulate broker going down and coming back up...
            this.rabbitAdmin.DeleteQueue(queue.Name);
            this.connectionFactory.Dispose();
            Assert.False(this.QueueExists(null, queue));

            // Broker auto-deleted queue, but it is re-created by the connection listener
            exists = rabbitTemplate.Execute<bool>(delegate(IModel channel)
            {
                var result = channel.QueueDeclarePassive(queue.Name);
                connectionHolder.LazySet(((CachedModel)channel).Connection);
                return result != null;
            });
            Assert.True(exists, "Expected Queue to exist");

            Assert.True(this.QueueExists(connectionHolder.Value, queue));
            Assert.True(this.rabbitAdmin.DeleteQueue(queue.Name));
            Assert.False(this.QueueExists(null, queue));
        }
        /// <summary>
        /// Queues the exists.
        /// </summary>
        /// <param name="connection">The connection.</param>
        /// <param name="queue">The queue.</param>
        /// <returns></returns>
        /// Use native Rabbit API to test queue, bypassing all the connection and channel caching and callbacks in Spring
        /// AMQP.
        /// @param connection the raw connection to use
        /// @param queue the Queue to test
        /// @return true if the queue exists
        /// <remarks></remarks>
        private bool QueueExists(IConnection connection, Queue queue)
        {
            var target = connection;
            if (target == null)
            {
                var connectionFactory = new ConnectionFactory();
                connectionFactory.Port = BrokerTestUtils.GetPort();
                target = connectionFactory.CreateConnection();
            }

            var channel = target.CreateModel();
            try
            {
                var result = channel.QueueDeclarePassive(queue.Name);
                return result != null;
            }
            catch (Exception e)
            {
                if (e.Message.Contains("RESOURCE_LOCKED"))
                {
                    return true;
                }

                return false;
            }
            finally
            {
                if (connection == null)
                {
                    target.Close();
                }
            }
        }
        public void TestQueueWithoutAutoDelete()
        {
            var queue = new Queue("test.queue", false, false, false);
            this.context.ObjectFactory.RegisterSingleton("foo", queue);
            this.rabbitAdmin.AfterPropertiesSet();

            // Queue created on Spring startup
            this.rabbitAdmin.Initialize();
            Assert.True(this.QueueExists(queue));

            // Stop and broker retains queue (only verifiable in native API)
            this.connectionFactory.Dispose();
            Assert.True(this.QueueExists(queue));

            // Start and queue still exists
            this.connectionFactory.CreateConnection();
            Assert.True(this.QueueExists(queue));

            // Queue manually deleted
            Assert.True(this.rabbitAdmin.DeleteQueue(queue.Name));
            Assert.False(this.QueueExists(queue));
        }
        /// <summary>
        /// Declares all the exchanges, queues and bindings in the enclosing application context, if any. It should be safe
        /// (but unnecessary) to call this method more than once.
        /// </summary>
        public void Initialize()
        {
            if (this.applicationContext == null)
            {
                Logger.Debug(m => m("no ApplicationContext has been set, cannot auto-declare Exchanges, Queues, and Bindings"));
                return;
            }

            Logger.Debug(m => m("Initializing declarations"));
            var exchanges = this.applicationContext.GetObjectsOfType(typeof(IExchange)).Values;
            var queues = this.applicationContext.GetObjectsOfType(typeof(Queue)).Values;
            var bindings = this.applicationContext.GetObjectsOfType(typeof(Binding)).Values;

            foreach (IExchange exchange in exchanges)
            {
                if (!exchange.Durable)
                {
                    Logger.Warn(m => m("Auto-declaring a non-durable Exchange ({0}). It will be deleted by the broker if it shuts down, and can be redeclared by closing and reopening the connection.", exchange.Name));
                }

                if (exchange.AutoDelete)
                {
                    Logger.Warn(
                        m =>
                        m("Auto-declaring an auto-delete Exchange ({0}). It will be deleted by the broker if not in use (if all bindings are deleted), but will only be redeclared if the connection is closed and reopened.", exchange.Name));
                }
            }

            foreach (Queue queue in queues)
            {
                if (!queue.Durable)
                {
                    Logger.Warn(m => m("Auto-declaring a non-durable Queue ({0}). It will be redeclared if the broker stops and is restarted while the connection factory is alive, but all messages will be lost.", queue.Name));
                }

                if (queue.AutoDelete)
                {
                    Logger.Warn(m => m("Auto-declaring an auto-delete Queue ({0}). It will be deleted by the broker if not in use, and all messages will be lost.  Redeclared when the connection is closed and reopened.", queue.Name));
                }

                if (queue.Exclusive)
                {
                    Logger.Warn(m => m("Auto-declaring an exclusive Queue ({0}). It cannot be accessed by consumers on another connection, and will be redeclared if the connection is reopened.", queue.Name));
                }
            }

            this.rabbitTemplate.Execute<object>(
                channel =>
                {
                    var exchangeArray = new IExchange[exchanges.Count];
                    var queueArray = new Queue[queues.Count];
                    var bindingArray = new Binding[bindings.Count];

                    exchanges.CopyTo(exchangeArray, 0);
                    queues.CopyTo(queueArray, 0);
                    bindings.CopyTo(bindingArray, 0);

                    this.DeclareExchanges(channel, exchangeArray);
                    this.DeclareQueues(channel, queueArray);
                    this.DeclareBindings(channel, bindingArray);
                    return null;
                });

            Logger.Debug(m => m("Declarations finished"));
        }
 public void DeclareQueue(Queue queue)
 {
     rabbitAdmin.DeclareQueue(queue);
 }
        /// <summary>
        /// Declares all the exchanges, queues and bindings in the enclosing application context, if any. It should be safe
        /// (but unnecessary) to call this method more than once.
        /// </summary>
        public void Initialize()
        {
            if (this.applicationContext == null)
            {
                Logger.Debug(m => m("no ApplicationContext has been set, cannot auto-declare Exchanges, Queues, and Bindings"));
                return;
            }

            Logger.Debug(m => m("Initializing declarations"));
            var exchanges = this.applicationContext.GetObjectsOfType(typeof(IExchange)).Values;
            var queues    = this.applicationContext.GetObjectsOfType(typeof(Queue)).Values;
            var bindings  = this.applicationContext.GetObjectsOfType(typeof(Binding)).Values;

            foreach (IExchange exchange in exchanges)
            {
                if (!exchange.Durable)
                {
                    Logger.Warn(m => m("Auto-declaring a non-durable Exchange ({0}). It will be deleted by the broker if it shuts down, and can be redeclared by closing and reopening the connection.", exchange.Name));
                }

                if (exchange.AutoDelete)
                {
                    Logger.Warn(
                        m =>
                        m("Auto-declaring an auto-delete Exchange ({0}). It will be deleted by the broker if not in use (if all bindings are deleted), but will only be redeclared if the connection is closed and reopened.", exchange.Name));
                }
            }

            foreach (Queue queue in queues)
            {
                if (!queue.Durable)
                {
                    Logger.Warn(m => m("Auto-declaring a non-durable Queue ({0}). It will be redeclared if the broker stops and is restarted while the connection factory is alive, but all messages will be lost.", queue.Name));
                }

                if (queue.AutoDelete)
                {
                    Logger.Warn(m => m("Auto-declaring an auto-delete Queue ({0}). It will be deleted by the broker if not in use, and all messages will be lost.  Redeclared when the connection is closed and reopened.", queue.Name));
                }

                if (queue.Exclusive)
                {
                    Logger.Warn(m => m("Auto-declaring an exclusive Queue ({0}). It cannot be accessed by consumers on another connection, and will be redeclared if the connection is reopened.", queue.Name));
                }
            }

            this.rabbitTemplate.Execute <object>(
                channel =>
            {
                var exchangeArray = new IExchange[exchanges.Count];
                var queueArray    = new Queue[queues.Count];
                var bindingArray  = new Binding[bindings.Count];

                exchanges.CopyTo(exchangeArray, 0);
                queues.CopyTo(queueArray, 0);
                bindings.CopyTo(bindingArray, 0);

                this.DeclareExchanges(channel, exchangeArray);
                this.DeclareQueues(channel, queueArray);
                this.DeclareBindings(channel, bindingArray);
                return(null);
            });

            Logger.Debug(m => m("Declarations finished"));
        }
 internal ExchangeConfigurer(Queue queue)
 {
     this.queue = queue;
 }
        /// <summary>
        /// Determines whether [is running with empty queues] [the specified names].
        /// </summary>
        /// <param name="names">The names.</param>
        /// Ensure the broker is running and has an empty queue with the specified name in the default exchange.
        /// @return a new rule that assumes an existing running broker
        /// <remarks></remarks>
        public static BrokerRunning IsRunningWithEmptyQueues(params string[] names)
        {
            var queues = new Queue[names.Length];
            for (var i = 0; i < queues.Length; i++)
            {
                queues[i] = new Queue(names[i]);
            }

            return new BrokerRunning(true, true, queues);
        }
 public void TestDoubleDeclarationOfAutodeleteQueue()
 {
     // No error expected here: the queue is autodeleted when the last consumer is cancelled, but this one never has
     // any consumers.
     var connectionFactory1 = new CachingConnectionFactory();
     connectionFactory1.Port = BrokerTestUtils.GetPort();
     var connectionFactory2 = new CachingConnectionFactory();
     connectionFactory2.Port = BrokerTestUtils.GetPort();
     var queue = new Queue("test.queue", false, false, true);
     new RabbitAdmin(connectionFactory1).DeclareQueue(queue);
     new RabbitAdmin(connectionFactory2).DeclareQueue(queue);
     connectionFactory1.Dispose();
     connectionFactory2.Dispose();
 }
 public ExchangeConfigurer From(Queue queue)
 {
     return new ExchangeConfigurer(queue);
 }
        public void TestDeclareBindingWithDefaultExchangeImplicitBinding()
        {
            var exchange = new DirectExchange(RabbitAdmin.DEFAULT_EXCHANGE_NAME);
            var queueName = "test.queue";
            var queue = new Queue(queueName, false, false, false);
            this.rabbitAdmin.DeclareQueue(queue);
            var binding = new Binding(queueName, Binding.DestinationType.Queue, exchange.Name, queueName, null);

            this.rabbitAdmin.DeclareBinding(binding);

            // Pass by virtue of RabbitMQ not firing a 403 reply code for both exchange and binding declaration
            Assert.True(this.QueueExists(queue));
        }
 public DirectExchangeRoutingKeyConfigurer(Queue queue, IExchange exchange)
     : base(queue, exchange)
 {
 }
Beispiel #36
0
 /// <summary>
 /// Declares the queue.
 /// </summary>
 /// <param name="queue">The queue.</param>
 public void DeclareQueue(Queue queue)
 {
     rabbitTemplate.Execute<object>(delegate(IModel channel)
     {
         channel.QueueDeclare(queue.Name, false, queue.Durable, queue.Exclusive, queue.AutoDelete, false,
                              queue.Arguments);
         return null;
     });
 }