コード例 #1
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);
            }
        }
コード例 #2
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);
            }
        }
コード例 #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.");
            }
        }
コード例 #4
0
        public void TestSendAndReceiveWithFanout()
        {
            var admin    = new RabbitAdmin(this.connectionFactory);
            var exchange = new FanoutExchange("fanout");

            admin.DeclareExchange(exchange);
            this.template.Exchange = exchange.Name;

            admin.DeclareBinding(BindingBuilder.Bind(queue).To(exchange));

            this.template.Execute <object>(
                delegate
            {
                var consumer = this.CreateConsumer(this.template);
                var tag      = consumer.ConsumerTag;
                Assert.IsNotNull(tag);

                try
                {
                    this.template.ConvertAndSend("message");
                    var result = this.GetResult(consumer);
                    Assert.AreEqual("message", result);
                }
                finally
                {
                    consumer.Stop();
                }

                return(null);
            });
        }
コード例 #5
0
        public DirectReplyToMessageListenerContainerTest()
        {
            var adminCf = new CachingConnectionFactory("localhost");
            var admin   = new RabbitAdmin(adminCf);

            admin.DeclareQueue(new Config.Queue(TEST_RELEASE_CONSUMER_Q));
        }
コード例 #6
0
        public void TestSendAndReceiveWithTopicConsumeInBackground()
        {
            var admin    = new RabbitAdmin(this.connectionFactory);
            var exchange = new TopicExchange("topic");

            admin.DeclareExchange(exchange);
            this.template.Exchange = exchange.Name;

            admin.DeclareBinding(BindingBuilder.Bind(queue).To(exchange).With("*.end"));

            var template = new RabbitTemplate(new CachingConnectionFactory());

            template.Exchange = exchange.Name;

            var consumer = this.template.Execute(
                delegate
            {
                var consumerinside = this.CreateConsumer(template);
                var tag            = consumerinside.ConsumerTag;
                Assert.IsNotNull(tag);

                return(consumerinside);
            });

            template.ConvertAndSend("foo", "message");
            var result = this.GetResult(consumer);

            Assert.AreEqual(null, result);

            this.template.ConvertAndSend("foo.end", "message");
            result = this.GetResult(consumer);
            Assert.AreEqual("message", result);

            consumer.Stop();
        }
コード例 #7
0
        public void TestSendAndReceiveWithNonDefaultExchange()
        {
            var admin    = new RabbitAdmin(this.connectionFactory);
            var exchange = new TopicExchange("topic");

            admin.DeclareExchange(exchange);

            admin.DeclareBinding(BindingBuilder.Bind(queue).To(exchange).With("*.end"));

            this.template.Execute <object>(
                delegate
            {
                var consumer = this.CreateConsumer(this.template);
                var tag      = consumer.ConsumerTag;
                Assert.IsNotNull(tag);

                this.template.ConvertAndSend("topic", "foo", "message");

                try
                {
                    var result = this.GetResult(consumer);
                    Assert.AreEqual(null, result);

                    this.template.ConvertAndSend("topic", "foo.end", "message");
                    result = this.GetResult(consumer);
                    Assert.AreEqual("message", result);
                }
                finally
                {
                    consumer.Channel.BasicCancel(tag);
                }

                return(null);
            });
        }
コード例 #8
0
 public RabbitTestBinder(IConnectionFactory connectionFactory, RabbitMessageChannelBinder binder, ILogger <RabbitTestBinder> logger)
 {
     _logger = logger;
     PollableConsumerBinder = binder;
     _rabbitAdmin           = new RabbitAdmin(GetApplicationContext(), connectionFactory, logger);
     BindingsOptions        = binder.BindingsOptions;
 }
コード例 #9
0
 public RabbitController(ILogger <RabbitController> logger, RabbitTemplate rabbitTemplate,
                         RabbitAdmin rabbitAdmin)
 {
     _logger         = logger;
     _rabbitTemplate = rabbitTemplate;
     _rabbitAdmin    = rabbitAdmin;
 }
コード例 #10
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();
            }
        }
コード例 #11
0
        public void Dispose()
        {
            var adminCf = new CachingConnectionFactory("localhost");
            var admin   = new RabbitAdmin(adminCf);

            admin.DeleteQueue(TEST_RELEASE_CONSUMER_Q);
            adminCf.Dispose();
        }
コード例 #12
0
        public void ShouldCreateVirtualHost()
        {
            var api = new RabbitAdmin("http://localhost:15672/api");

            api.Delete(new VirtualHost("test"));

            Assert.That(api.Create(new VirtualHost("test")));
            Assert.That(api.VirtualHosts.Any(v => v.Name == "test"));
        }
コード例 #13
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;
 }
        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));
        }
コード例 #15
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");
            }
        }
コード例 #16
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);
        }
        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);
        }
コード例 #18
0
        public RabbitExchangeQueueProvisioner(IConnectionFactory connectionFactory, List <IDeclarableCustomizer> customizers, IOptionsMonitor <RabbitBindingsOptions> bindingsOptions, IApplicationContext applicationContext, ILogger <RabbitExchangeQueueProvisioner> logger)
        {
            Admin = new RabbitAdmin(applicationContext, connectionFactory, logger);

            _autoDeclareContext      = applicationContext;
            _logger                  = logger;
            Admin.ApplicationContext = _autoDeclareContext;
            Admin.Initialize();
            Customizers = customizers;
            Options     = bindingsOptions.CurrentValue;
        }
コード例 #19
0
        public void Init()
        {
            this.context = new GenericApplicationContext();
            this.rabbitAdmin = new RabbitAdmin(this.connectionFactory);

            this.rabbitAdmin.DeleteQueue("test.queue");

            // Force connection factory to forget that it has been used to delete the queue
            this.connectionFactory.Dispose();
            this.rabbitAdmin.ApplicationContext = this.context;
            this.rabbitAdmin.AutoStartup = true;
        }
コード例 #20
0
        public void TestGetQueues()
        {
            AbstractConnectionFactory connectionFactory = new SingleConnectionFactory();

            connectionFactory.Port = BrokerTestUtils.GetAdminPort();
            Queue queue = new RabbitAdmin(connectionFactory).DeclareQueue();

            Assert.AreEqual("/", connectionFactory.VirtualHost);
            List <QueueInfo> queues = this.brokerAdmin.GetQueues();

            Assert.AreEqual(queue.Name, queues[0].Name);
        }
コード例 #21
0
        public RabbitExchangeQueueProvisioner(IConnectionFactory connectionFactory, List <IDeclarableCustomizer> customizers, RabbitBindingsOptions bindingsOptions, IApplicationContext applicationContext, ILogger <RabbitExchangeQueueProvisioner> logger)
        {
            Admin = new RabbitAdmin(applicationContext, connectionFactory, logger);

            var serviceProvider = new ServiceCollection().BuildServiceProvider();

            _autoDeclareContext      = applicationContext;
            _logger                  = logger;
            Admin.ApplicationContext = _autoDeclareContext;
            Admin.Initialize();
            Customizers = customizers;
            Options     = bindingsOptions;
        }
コード例 #22
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();
コード例 #23
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);
        }
コード例 #24
0
        public void TestNoFailOnStartupWithMissingBroker()
        {
            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();
        }
コード例 #25
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();
            }
        }
コード例 #26
0
ファイル: Program.cs プロジェクト: nikhilkrishna/Samples
        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);
        }
コード例 #27
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);
            }
        }
コード例 #28
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();
            }
        }
コード例 #29
0
        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);
            }));
        }