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(); }
public RabbitController(ILogger <RabbitController> logger, RabbitTemplate rabbitTemplate, RabbitAdmin rabbitAdmin) { _logger = logger; _rabbitTemplate = rabbitTemplate; _rabbitAdmin = rabbitAdmin; }
public RabbitBrokerAdmin(IConnectionFactory connectionFactory) { this.virtualHost = connectionFactory.VirtualHost; this.rabbitTemplate = new RabbitTemplate(connectionFactory); this.rabbitAdmin = new RabbitAdmin(rabbitTemplate); InitializeDefaultErlangTemplate(rabbitTemplate); }
public void TestReceiveFromNonExistentVirtualHost() { connectionFactory.VirtualHost = "non-existent"; var template = new RabbitTemplate(connectionFactory); Assert.Throws <RabbitConnectException>(() => template.ReceiveAndConvert <string>("foo")); }
public void DontHangConsumerThread() { 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 consumer = new AtomicReference <RC.IBasicConsumer>(); mockChannel.Setup((c) => c.QueueDeclare(It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <IDictionary <string, object> >())) .Returns(new RC.QueueDeclareOk("foo", 0, 0)); mockChannel.Setup((c) => c.BasicConsume(It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <IDictionary <string, object> >(), It.IsAny <RC.IBasicConsumer>())) .Callback <string, bool, string, bool, bool, IDictionary <string, object>, RC.IBasicConsumer>((arg1, arg2, arg3, arg4, arg5, arg6, arg7) => consumer.Value = arg7); var connectionFactory = new SingleConnectionFactory(mockConnectionFactory.Object); var template = new RabbitTemplate(connectionFactory) { ReplyTimeout = 1 }; var payload = EncodingUtils.GetDefaultEncoding().GetBytes("Hello, world!"); var input = Message.Create(payload, new MessageHeaders()); template.DoSendAndReceiveWithTemporary("foo", "bar", input, null, default); // used to hang here because of the SynchronousQueue and doSendAndReceive() already exited consumer.Value.HandleBasicDeliver("foo", 1ul, false, "foo", "bar", new MockRabbitBasicProperties(), new byte[0]); }
public void TestListenerSendsMessageAndThenContainerCommits() { var connectionFactory = this.CreateConnectionFactory(); var template = new RabbitTemplate(connectionFactory); new RabbitAdmin(connectionFactory).DeclareQueue(sendQueue); this.acknowledgeMode = AcknowledgeModeUtils.AcknowledgeMode.Auto; this.transactional = true; var latch = new CountdownEvent(1); this.container = this.CreateContainer(queue.Name, new ChannelSenderListener(sendQueue.Name, latch, false), connectionFactory); template.ConvertAndSend(queue.Name, "foo"); var timeout = this.GetTimeout(); Logger.Debug("Waiting for messages with timeout = " + timeout + " (s)"); var waited = latch.Wait(new TimeSpan(0, 0, timeout)); Assert.True(waited, "Timed out waiting for message"); Thread.Sleep(500); // All messages committed var bytes = (byte[])template.ReceiveAndConvert(sendQueue.Name); Assert.NotNull(bytes); Assert.AreEqual("bar", Encoding.UTF8.GetString(bytes)); Assert.AreEqual(null, template.ReceiveAndConvert(queue.Name)); }
public void ReturnConnectionAfterCommit() { var txTemplate = new TransactionTemplate(new RabbitTemplateTestsTransactionManager()); 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.IsOpen).Returns(true); mockChannel.Setup(m => m.CreateBasicProperties()).Returns(() => new BasicProperties()); var template = new RabbitTemplate(new CachingConnectionFactory(mockConnectionFactory.Object)); template.ChannelTransacted = true; txTemplate.Execute( status => { template.ConvertAndSend("foo", "bar"); return null; }); txTemplate.Execute( status => { template.ConvertAndSend("baz", "qux"); return null; }); mockConnectionFactory.Verify(m => m.CreateConnection(), Times.Once()); // ensure we used the same channel mockConnection.Verify(m => m.CreateModel(), Times.Once()); }
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."); } }
[Test] // AMQP-249 public void DontHangConsumerThread() { 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.QueueDeclare()).Returns(new QueueDeclareOk("foo", 0, 0)); mockChannel.Setup(m => m.CreateBasicProperties()).Returns(() => new BasicProperties()); var consumer = new AtomicReference <DefaultBasicConsumer>(); mockChannel.Setup(m => m.BasicConsume(It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <IDictionary>(), It.IsAny <IBasicConsumer>())).Callback <string, bool, string, bool, bool, IDictionary, IBasicConsumer>( (a1, a2, a3, a4, a5, a6, a7) => consumer.LazySet((DefaultBasicConsumer)a7)); var template = new RabbitTemplate(new SingleConnectionFactory(mockConnectionFactory.Object)); template.ReplyTimeout = 1; var input = new Message(Encoding.UTF8.GetBytes("Hello, world!"), new MessageProperties()); var doSendAndReceiveWithTemporaryMethod = typeof(RabbitTemplate).GetMethod("DoSendAndReceiveWithTemporary", BindingFlags.NonPublic | BindingFlags.Instance); doSendAndReceiveWithTemporaryMethod.Invoke(template, new object[] { "foo", "bar", input }); var envelope = new BasicGetResult(1, false, "foo", "bar", 0, new BasicProperties(), null); // used to hang here because of the SynchronousQueue and DoSendAndReceive() already exited consumer.Value.HandleBasicDeliver("foo", envelope.DeliveryTag, envelope.Redelivered, envelope.Exchange, envelope.RoutingKey, new BasicProperties(), new byte[0]); }
public void TestListenerSendsMessageAndThenRollback() { var connectionFactory = this.CreateConnectionFactory(); var template = new RabbitTemplate(connectionFactory); new RabbitAdmin(connectionFactory).DeclareQueue(sendQueue); this.acknowledgeMode = AcknowledgeModeUtils.AcknowledgeMode.Auto; this.transactional = true; var latch = new CountdownEvent(1); this.container = this.CreateContainer(queue.Name, new ChannelSenderListener(sendQueue.Name, latch, true), connectionFactory); template.ConvertAndSend(queue.Name, "foo"); var timeout = this.GetTimeout(); Logger.Debug("Waiting for messages with timeout = " + timeout + " (s)"); var waited = latch.Wait(timeout * 1000); Assert.True(waited, "Timed out waiting for message"); this.container.Stop(); Thread.Sleep(200); // Foo message is redelivered Assert.AreEqual("foo", template.ReceiveAndConvert(queue.Name)); // Sending of bar message is also rolled back Assert.Null(template.ReceiveAndConvert(sendQueue.Name)); }
public void TestEvaluateDirectReplyToWithIOExceptionDeclareFailed() { 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()); mockChannel.Setup((c) => c.QueueDeclare(It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <IDictionary <string, object> >())) .Returns(() => new RC.QueueDeclareOk("foo", 0, 0)); mockChannel.Setup((c) => c.QueueDeclarePassive(Address.AMQ_RABBITMQ_REPLY_TO)).Throws(new ShutdownSignalException(new RC.ShutdownEventArgs(RC.ShutdownInitiator.Peer, RabbitUtils.NotFound, string.Empty, RabbitUtils.Queue_ClassId, RabbitUtils.Declare_MethodId))); var connectionFactory = new SingleConnectionFactory(mockConnectionFactory.Object); var template = new RabbitTemplate(connectionFactory) { ReplyTimeout = 1 }; template.ConvertSendAndReceive <object>("foo"); Assert.True(template._evaluatedFastReplyTo); Assert.False(template._usingFastReplyTo); }
public void TestRetry() { var mockConnectionFactory = new Mock <RC.IConnectionFactory>(); var count = new AtomicInteger(); mockConnectionFactory.Setup((f) => f.CreateConnection(It.IsAny <string>())) .Callback(() => count.IncrementAndGet()) .Throws(new AuthenticationFailureException("foo")); var connectionFactory = new SingleConnectionFactory(mockConnectionFactory.Object); var template = new RabbitTemplate(connectionFactory) { RetryTemplate = new PollyRetryTemplate(new Dictionary <Type, bool>(), 3, true, 1, 1, 1) }; try { template.ConvertAndSend("foo", "bar", "baz"); } catch (RabbitAuthenticationException e) { Assert.Contains("foo", e.InnerException.Message); } Assert.Equal(3, count.Value); }
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(); }
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); }
public void TestWithinInvoke() { var connectionFactory = new Mock <Connection.IConnectionFactory>(); var connection = new Mock <Connection.IConnection>(); connectionFactory.Setup((f) => f.CreateConnection()).Returns(connection.Object); var channel1 = new Mock <RC.IModel>(); var channel2 = new Mock <RC.IModel>(); connection.SetupSequence((c) => c.CreateChannel(false)).Returns(channel1.Object).Returns(channel2.Object); var declareOk = new RC.QueueDeclareOk("foo", 0, 0); channel1.Setup((c) => c.QueueDeclare(It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <IDictionary <string, object> >())).Returns(declareOk); var template = new RabbitTemplate(connectionFactory.Object); var admin = new RabbitAdmin(template); template.Invoke <object>((o) => { admin.DeclareQueue(); admin.DeclareQueue(); admin.DeclareQueue(); admin.DeclareQueue(); return(null); }); connection.Verify((c) => c.CreateChannel(false), Times.Once); channel1.Verify((c) => c.QueueDeclare(It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <IDictionary <string, object> >()), Times.Exactly(4)); channel1.Verify((c) => c.Close(), Times.Once); channel2.VerifyNoOtherCalls(); }
private void OldSendMessages(RabbitTemplate template) { IBasicProperties basicProperties = template.Execute<IBasicProperties>(delegate(IModel model) { return model.CreateBasicProperties(); }); /* * System.ArgumentNullException: String reference not set to an instance of a String. Parameter name: s at System.Text.Encoding.GetBytes(String s) at RabbitMQ.Client.Impl.WireFormatting.WriteShortstr(NetworkBinaryWriter writer, String val) */ IMessageProperties messageProperties = new MessageProperties(basicProperties); //write all short props messageProperties.ContentType = "text/plain"; messageProperties.ContentEncoding = "UTF-8"; messageProperties.CorrelationId = Encoding.UTF8.GetBytes("corr1"); messageProperties.DeliveryMode = MessageDeliveryMode.PERSISTENT; messageProperties.Priority = 0; byte[] byteMessage = Encoding.UTF8.GetBytes("testing"); template.Send("amq.direct", "foo", delegate { Message msg = new Message(byteMessage, messageProperties); Console.WriteLine("sending..."); return msg; }); //template.Send("amq.direct", "foo", channel => new Message(Encoding.UTF8.GetBytes("testing"), messageProperties)); }
public void TestListenerRecoversFromClosedChannelAndStop() { var template = new RabbitTemplate(this.CreateConnectionFactory()); var latch = new CountdownEvent(this.messageCount); this.container = this.CreateContainer(queue.Name, new AbortChannelListener(latch), this.CreateConnectionFactory()); var n = 0; while (n++ < 100 && this.container.ActiveConsumerCount != this.concurrentConsumers) { Thread.Sleep(50); } Assert.AreEqual(this.concurrentConsumers, this.container.ActiveConsumerCount); for (var i = 0; i < this.messageCount; i++) { template.ConvertAndSend(queue.Name, i + "foo"); } var timeout = this.GetTimeout(); Logger.Debug("Waiting for messages with timeout = " + timeout + " (s)"); var waited = latch.Wait(new TimeSpan(0, 0, timeout)); Assert.True(waited, "Timed out waiting for message"); Assert.Null(template.ReceiveAndConvert(queue.Name)); Assert.AreEqual(this.concurrentConsumers, this.container.ActiveConsumerCount); this.container.Stop(); Assert.AreEqual(0, this.container.ActiveConsumerCount); }
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(); } }
public void TestConvertBytes() { var template = new RabbitTemplate(); var payload = EncodingUtils.GetDefaultEncoding().GetBytes("Hello, world!"); var message = template.ConvertMessageIfNecessary(payload); Assert.Same(payload, message.Payload); }
public void OnMessage(IMessage message) { var template = new RabbitTemplate(_connectionFactory); template.IsChannelTransacted = true; template.ConvertAndSend("foo", "bar", "baz"); _latch.Signal(); }
public void TestAtomicSendAndReceiveWithConversionAndMessagePostProcessor() { var template = new RabbitTemplate(new CachingConnectionFactory()); template.RoutingKey = ROUTE; template.Queue = ROUTE; // ExecutorService executor = Executors.newFixedThreadPool(1); // Set up a consumer to respond to our producer var received = Task.Factory.StartNew( () => { Message message = null; for (var i = 0; i < 10; i++) { message = template.Receive(); if (message != null) { break; } Thread.Sleep(100); } Assert.IsNotNull(message, "No message received"); template.Send(message.MessageProperties.ReplyTo, message); return((string)template.MessageConverter.FromMessage(message)); }); var result = (string)template.ConvertSendAndReceive( "message", message => { try { byte[] newBody = Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(message.Body).ToUpper()); return(new Message(newBody, message.MessageProperties)); } catch (Exception e) { throw new AmqpException("unexpected failure in test", e); } }); var success = received.Wait(1000); if (!success) { Assert.Fail("Timed out receiving the message."); } Assert.AreEqual("MESSAGE", received.Result); Assert.AreEqual("MESSAGE", result); // Message was consumed so nothing left on queue result = (string)template.ReceiveAndConvert(); Assert.AreEqual(null, result); }
public void TestConvertMessage() { var template = new RabbitTemplate(); var payload = EncodingUtils.GetDefaultEncoding().GetBytes("Hello, world!"); var input = Message.Create(payload, new MessageHeaders()); var message = template.ConvertMessageIfNecessary(input); Assert.Same(message, input); }
public void TestConvertString() { var template = new RabbitTemplate(); var payload = "Hello, world!"; var message = template.ConvertMessageIfNecessary(payload); var messageString = EncodingUtils.GetDefaultEncoding().GetString((byte[])message.Payload); Assert.Equal(payload, messageString); }
public void TestNoListenerAllowed2() { var template = new RabbitTemplate { ReplyAddress = Address.AMQ_RABBITMQ_REPLY_TO }; Assert.Throws <InvalidOperationException>(() => template.GetExpectedQueueNames()); }
public void TestConvertSerializable() { var template = new RabbitTemplate(); var payload = 43L; var convertMessageIfNecessaryMethod = typeof(RabbitTemplate).GetMethod("ConvertMessageIfNecessary", BindingFlags.NonPublic | BindingFlags.Instance); var message = (Message)convertMessageIfNecessaryMethod.Invoke(template, new object[] { payload }); Assert.AreEqual(payload, SerializationUtils.DeserializeObject(message.Body)); }
public void TestConvertMessage() { var template = new RabbitTemplate(); var input = new Message(Encoding.UTF8.GetBytes("Hello, world!"), new MessageProperties()); var convertMessageIfNecessaryMethod = typeof(RabbitTemplate).GetMethod("ConvertMessageIfNecessary", BindingFlags.NonPublic | BindingFlags.Instance); var message = (Message)convertMessageIfNecessaryMethod.Invoke(template, new object[] { input }); Assert.AreSame(input, message); }
public void TestConvertString() { var template = new RabbitTemplate(); var payload = "Hello, world!"; var convertMessageIfNecessaryMethod = typeof(RabbitTemplate).GetMethod("ConvertMessageIfNecessary", BindingFlags.NonPublic | BindingFlags.Instance); var message = (Message)convertMessageIfNecessaryMethod.Invoke(template, new[] { payload }); Assert.AreEqual(payload, Encoding.GetEncoding(SimpleMessageConverter.DEFAULT_CHARSET).GetString(message.Body)); }
public void Create() { this.brokerIsRunning = BrokerRunning.IsRunningWithEmptyQueues(ROUTE); this.brokerIsRunning.Apply(); var connectionFactory = new CachingConnectionFactory(); connectionFactory.Port = BrokerTestUtils.GetPort(); this.template = new RabbitTemplate(connectionFactory); }
public void Send(TradeRequest tradeRequest) { RabbitTemplate.ConvertAndSend(tradeRequest, delegate(Message message) { message.MessageProperties.ReplyToAddress = new Address(defaultReplyToQueue); message.MessageProperties.CorrelationId = new Guid().ToByteArray(); return(message); }); }
protected RabbitTemplate CreateSendAndReceiveRabbitTemplate(IConnectionFactory connectionFactory) { var template = new RabbitTemplate(connectionFactory) { UseDirectReplyToContainer = false }; return(template); }
public void FixtureSetup() { IConnectionFactory connectionFactory = new CachingConnectionFactory(); template = new RabbitTemplate(); template.ConnectionFactory = connectionFactory; template.ChannelTransacted = true; template.AfterPropertiesSet(); }
public void Init() { var connectionFactory = new CachingConnectionFactory(); this.template = new RabbitTemplate(connectionFactory); this.template.IsChannelTransacted = true; var transactionManager = new RabbitTransactionManager(connectionFactory); this.transactionTemplate = new TransactionTemplate(transactionManager); this.transactionTemplate.TransactionIsolationLevel = IsolationLevel.Unspecified; }
public void DeleteQueue(string queueName, bool unused, bool empty) { RabbitTemplate.Execute <object>( channel => { channel.QueueDelete(queueName, unused, empty); return(null); }); }
public void TestRabbitGatewaySupportWithJmsTemplate() { var template = new RabbitTemplate(); var test = new List<string>(); var gateway = new TestGateway(test); gateway.RabbitTemplate = template; gateway.AfterPropertiesSet(); Assert.AreEqual(template, gateway.RabbitTemplate, "Correct RabbitTemplate"); Assert.AreEqual(test.Count, 1, "initGateway called"); }
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)); }
public uint PurgeQueue(string queueName) { return(RabbitTemplate.Execute( channel => { var queuePurged = channel.QueuePurge(queueName); _logger?.LogDebug("Purged queue: {queuename} : {result}", queueName, queuePurged); return queuePurged; })); }
/// <summary>Sends the messages.</summary> /// <param name="template">The template.</param> /// <param name="exchange">The exchange.</param> /// <param name="routingKey">The routing key.</param> /// <param name="numMessages">The num messages.</param> private static void SendMessages(RabbitTemplate template, string exchange, string routingKey, int numMessages) { for (int i = 1; i <= numMessages; i++) { byte[] bytes = Encoding.UTF8.GetBytes("testing"); var properties = new MessageProperties(); properties.Headers.Add("float", 3.14); var message = new Message(bytes, properties); template.Send(exchange, routingKey, message); Console.WriteLine("sending " + i + "..."); } }
/// <summary> /// Declares the test queue. /// </summary> /// <param name="template">The template.</param> /// <param name="routingKey">The routing key.</param> /// <remarks></remarks> public static void DeclareTestQueue(RabbitTemplate template, string routingKey) { // declare and bind queue template.Execute<string>(delegate(IModel channel) { var queueName = channel.QueueDeclarePassive(TestConstants.QUEUE_NAME); // String queueName = res.GetQueue(); Console.WriteLine("Queue Name = " + queueName); channel.QueueBind(queueName, TestConstants.EXCHANGE_NAME, routingKey); return queueName; }); }
private void ReceiveSync(RabbitTemplate template, int numMessages) { for (int i = 0; i < numMessages; i++) { string msg = (string) template.ReceiveAndConvert("foo"); if (msg == null) { Console.WriteLine("Thread [" + Thread.CurrentThread.ManagedThreadId + "] " + "Recieved null message!"); } else { Console.WriteLine("Thread [" + Thread.CurrentThread.ManagedThreadId + "] " + msg); } } }
public void TestTransactionalLowLevel() { var template = new RabbitTemplate(); var connectionFactory = new CachingConnectionFactory(); connectionFactory.Port = BrokerTestUtils.GetPort(); template.ConnectionFactory = connectionFactory; var blockingQueueConsumer = new BlockingQueueConsumer(connectionFactory, new DefaultMessagePropertiesConverter(), new ActiveObjectCounter<BlockingQueueConsumer>(), AcknowledgeModeUtils.AcknowledgeMode.Auto, true, 1, queue.Name); blockingQueueConsumer.Start(); connectionFactory.Dispose(); // TODO: make this into a proper assertion. An exception can be thrown here by the Rabbit client and printed to // stderr without being rethrown (so hard to make a test fail). blockingQueueConsumer.Stop(); Assert.IsNull(template.ReceiveAndConvert(queue.Name)); }
private void SendMessages(RabbitTemplate template, string exchange, string routingKey, int numMessages) { for (int i = 1; i <= numMessages; i++) { Console.WriteLine("sending..."); template.ConvertAndSend(exchange, routingKey, "test-" + i); /* template.Send(exchange, routingKey, delegate { return new Message(Encoding.UTF8.GetBytes("testing"), template.CreateMessageProperties()); }); */ } ; }
/// <summary>Mains the specified args.</summary> /// <param name="args">The args.</param> public static void Main(string[] args) { var connectionFactory = new SingleConnectionFactory("localhost"); connectionFactory.UserName = "******"; connectionFactory.Password = "******"; var template = new RabbitTemplate(); template.ConnectionFactory = connectionFactory; template.ChannelTransacted = true; template.AfterPropertiesSet(); var routingKey = TestConstants.ROUTING_KEY; QueueUtils.DeclareTestQueue(template, routingKey); // Send message SendMessages(template, TestConstants.EXCHANGE_NAME, routingKey, TestConstants.NUM_MESSAGES); }
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); }
protected RabbitTemplate InitializeAndCreateTemplate() { connectionFactory = new CachingConnectionFactory(); RabbitTemplate template = new RabbitTemplate(); template.ConnectionFactory = connectionFactory; template.ChannelTransacted = true; template.AfterPropertiesSet(); //Declare queue and bind to a specific exchange. template.Execute<object>(delegate(IModel model) { model.QueueDeclare(TestConstants.QUEUE_NAME); model.QueueBind(TestConstants.QUEUE_NAME, TestConstants.EXCHANGE_NAME, TestConstants.ROUTING_KEY, false, null); return null; }); return template; }
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]); }
public void TestPushPop() { var template = new RabbitTemplate(); var pushHeaderMethod = typeof(RabbitTemplate).GetMethod("PushHeaderValue", BindingFlags.NonPublic | BindingFlags.Instance); var header = (string)pushHeaderMethod.Invoke(template, new object[] { "a", null }); Assert.AreEqual("a", header); header = (string)pushHeaderMethod.Invoke(template, new object[] { "b", header }); Assert.AreEqual("b:a", header); header = (string)pushHeaderMethod.Invoke(template, new object[] { "c", header }); Assert.AreEqual("c:b:a", header); var popHeaderMethod = typeof(RabbitTemplate).GetMethod("PopHeaderValue", BindingFlags.NonPublic | BindingFlags.Instance); var poppedHeader = popHeaderMethod.Invoke(template, new object[] { header }); var poppedValueField = poppedHeader.GetType().GetField("poppedValue", BindingFlags.NonPublic | BindingFlags.Instance); var newValueField = poppedHeader.GetType().GetField("newValue", BindingFlags.NonPublic | BindingFlags.Instance); Assert.AreEqual("c", poppedValueField.GetValue(poppedHeader)); poppedHeader = popHeaderMethod.Invoke(template, new[] { newValueField.GetValue(poppedHeader) }); Assert.AreEqual("b", poppedValueField.GetValue(poppedHeader)); poppedHeader = popHeaderMethod.Invoke(template, new[] { newValueField.GetValue(poppedHeader) }); Assert.AreEqual("a", poppedValueField.GetValue(poppedHeader)); Assert.IsNull(newValueField.GetValue(poppedHeader)); }
private RabbitTemplate CreateTemplate(int concurrentConsumers) { var template = new RabbitTemplate(); // SingleConnectionFactory connectionFactory = new SingleConnectionFactory(); var connectionFactory = new CachingConnectionFactory(); connectionFactory.ChannelCacheSize = concurrentConsumers; connectionFactory.Port = BrokerTestUtils.GetPort(); template.ConnectionFactory = connectionFactory; return template; }
public void TestSendAndReceiveFromVolatileQueue() { var template = new RabbitTemplate(this.connectionFactory); var admin = new RabbitAdmin(this.connectionFactory); var queue = admin.DeclareQueue(); template.ConvertAndSend(queue.Name, "message"); var result = (string)template.ReceiveAndConvert(queue.Name); Assert.AreEqual("message", result); }
public void TestReceiveFromNonExistentVirtualHost() { this.connectionFactory.VirtualHost = "non-existent"; var template = new RabbitTemplate(this.connectionFactory); // Wrong vhost is very unfriendly to client - the exception has no clue (just an EOF) // exception.expect(AmqpIOException.class); try { var result = (string)template.ReceiveAndConvert("foo"); Assert.AreEqual("message", result); } catch (Exception e) { Assert.True(e is AmqpIOException); } }
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); } }
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."); } }
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 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<BlockingQueueConsumer>(delegate(IModel channel) { 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); try { consumer.Model.BasicCancel(consumer.ConsumerTag); } catch (Exception e) { // TODO: this doesn't make sense. Looks like there is a bug in the rabbitmq.client code here: http://hg.rabbitmq.com/rabbitmq-dotnet-client/file/2f12b3b4d6bd/projects/client/RabbitMQ.Client/src/client/impl/ModelBase.cs#l1018 Console.WriteLine(e.Message); } }
public void TestConvertBytes() { var template = new RabbitTemplate(); byte[] payload = Encoding.UTF8.GetBytes("Hello, world!"); var convertMessageIfNecessaryMethod = typeof(RabbitTemplate).GetMethod("ConvertMessageIfNecessary", BindingFlags.NonPublic | BindingFlags.Instance); var message = (Message)convertMessageIfNecessaryMethod.Invoke(template, new[] { payload }); Assert.AreSame(payload, message.Body); }
/// <summary> /// Initializes a new instance of the <see cref="T:System.Object"/> class. /// </summary> /// <remarks></remarks> public RabbitBindingIntegrationTests() { this.template = new RabbitTemplate(this.connectionFactory); }
public void TestListenerRecoversFromDeadBroker() { var queues = this.brokerAdmin.GetQueues(); Logger.Info("Queues: " + queues); Assert.AreEqual(1, queues.Count); Assert.True(queues[0].Durable); var template = new RabbitTemplate(this.connectionFactory); var latch = new CountdownEvent(this.messageCount); Assert.AreEqual(this.messageCount, latch.CurrentCount, "No more messages to receive before even sent!"); this.container = this.CreateContainer(this.queue.Name, new VanillaListener(latch), this.connectionFactory); for (var i = 0; i < this.messageCount; i++) { template.ConvertAndSend(this.queue.Name, i + "foo"); } Assert.True(latch.CurrentCount > 0, "No more messages to receive before broker stopped"); Logger.Info(string.Format("Latch.CurrentCount Before Shutdown: {0}", latch.CurrentCount)); this.brokerAdmin.StopBrokerApplication(); Assert.True(latch.CurrentCount > 0, "No more messages to receive after broker stopped"); Logger.Info(string.Format("Latch.CurrentCount After Shutdown: {0}", latch.CurrentCount)); var waited = latch.Wait(500); Assert.False(waited, "Did not time out waiting for message"); this.container.Stop(); Assert.AreEqual(0, this.container.ActiveConsumerCount); Logger.Info(string.Format("Latch.CurrentCount After Container Stop: {0}", latch.CurrentCount)); this.brokerAdmin.StartBrokerApplication(); queues = this.brokerAdmin.GetQueues(); Logger.Info("Queues: " + queues); this.container.Start(); Logger.Info(string.Format("Concurrent Consumers After Container Start: {0}", this.container.ActiveConsumerCount)); Assert.AreEqual(this.concurrentConsumers, this.container.ActiveConsumerCount); Logger.Info(string.Format("Latch.CurrentCount After Container Start: {0}", latch.CurrentCount)); var timeout = Math.Min((4 + this.messageCount) / (4 * this.concurrentConsumers), 30); Logger.Debug("Waiting for messages with timeout = " + timeout + " (s)"); waited = latch.Wait(timeout * 1000); Assert.True(waited, "Timed out waiting for message"); Assert.IsNull(template.ReceiveAndConvert(this.queue.Name)); }
[Test] // AMQP-249 public void DontHangConsumerThread() { 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.QueueDeclare()).Returns(new QueueDeclareOk("foo", 0, 0)); mockChannel.Setup(m => m.CreateBasicProperties()).Returns(() => new BasicProperties()); var consumer = new AtomicReference<DefaultBasicConsumer>(); mockChannel.Setup(m => m.BasicConsume(It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<bool>(), It.IsAny<IDictionary>(), It.IsAny<IBasicConsumer>())).Callback <string, bool, string, bool, bool, IDictionary, IBasicConsumer>( (a1, a2, a3, a4, a5, a6, a7) => consumer.LazySet((DefaultBasicConsumer)a7)); var template = new RabbitTemplate(new SingleConnectionFactory(mockConnectionFactory.Object)); template.ReplyTimeout = 1; var input = new Message(Encoding.UTF8.GetBytes("Hello, world!"), new MessageProperties()); var doSendAndReceiveWithTemporaryMethod = typeof(RabbitTemplate).GetMethod("DoSendAndReceiveWithTemporary", BindingFlags.NonPublic | BindingFlags.Instance); doSendAndReceiveWithTemporaryMethod.Invoke(template, new object[] { "foo", "bar", input }); var envelope = new BasicGetResult(1, false, "foo", "bar", 0, new BasicProperties(), null); // used to hang here because of the SynchronousQueue and DoSendAndReceive() already exited consumer.Value.HandleBasicDeliver("foo", envelope.DeliveryTag, envelope.Redelivered, envelope.Exchange, envelope.RoutingKey, new BasicProperties(), new byte[0]); }