Esempio n. 1
0
        public async Task MutipleHost()
        {
            IServiceCollection services = new ServiceCollection();

            services.AddLogging();
            services.Configure <RabbitMQOptionCollection>(o =>
            {
                o.Add(new RabbitMQOption
                {
                    HostName    = "localhost",
                    Port        = 5672,
                    UserName    = "******",
                    Password    = "******",
                    VirtualHost = "test_mq",
                    Name        = "host1_test_mq"              // required when using IchannelPoolCollection
                });

                o.Add(new RabbitMQOption
                {
                    HostName    = "localhost",
                    Port        = 5672,
                    UserName    = "******",
                    Password    = "******",
                    VirtualHost = "test_mq",
                    Name        = "host1_test_mq1"              // required when using IchannelPoolCollection
                });
            });
            services.AddRabbitMQProducerService();


            ServiceProvider  serviceProvider = services.BuildServiceProvider();
            IMessageProducer transport       = serviceProvider.GetService <IMessageProducer>();

            // send to 'host1_test_mq'
            await transport.SendAsync(new Message <string>(
                                          new Dictionary <string, string> {
                { Generic.Headers.Exchange, "test.ex.v1" },
                { Generic.Headers.QueueName, "test.queue.v1" },
                { Generic.Headers.RoutingKey, "test.rk.v1" },
                { Generic.Headers.ExchangeType, ExchangeType.Direct },
                { Generic.Headers.Name, "host1_test_mq" }
            }, "你好呀"));

            // send to 'host1_test_mq1'
            await transport.SendAsync(new Message <string>(
                                          new Dictionary <string, string> {
                { Generic.Headers.Exchange, "test.ex.v2 " },
                { Generic.Headers.QueueName, "test.queue.v2" },
                { Generic.Headers.RoutingKey, "test.rk.v1" },
                { Generic.Headers.ExchangeType, ExchangeType.Direct },
                { Generic.Headers.Name, "host1_test_mq1" }
            }, "你好呀"));

            // send to 'host2_first'
            //await transport.SendAsync(new TransportMessage(new Dictionary<string, string> { { Generic.Headers.QueueName, "test.queue" }, { Generic.Headers.Name, "host2_first" } }, Encoding.UTF8.GetBytes("你好呀")));
        }
        public async Task TestSentAsync()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                IConnection connection = await base.EstablishConnectionAsync(testPeer);

                testPeer.ExpectBegin();
                testPeer.ExpectSenderAttach();

                ISession session = await connection.CreateSessionAsync(AcknowledgementMode.AutoAcknowledge);

                IQueue queue = await session.GetQueueAsync("myQueue");

                IMessageProducer producer = await session.CreateProducerAsync(queue);

                // Create and transfer a new message
                String text = "myMessage";
                testPeer.ExpectTransfer(messageMatcher: m => Assert.AreEqual(text, (m.BodySection as AmqpValue).Value),
                                        settled: false,
                                        sendResponseDisposition: true,
                                        responseState: new Accepted(),
                                        responseSettled: true,
                                        stateMatcher: Assert.IsNull,
                                        dispositionDelay: 10); // 10ms should be enough
                testPeer.ExpectClose();

                ITextMessage message = await session.CreateTextMessageAsync(text);

                await producer.SendAsync(message);

                await connection.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(1000);
            }
        }
Esempio n. 3
0
        public async Task TestProducerSendWithExpiry()
        {
            // Uri uri = new Uri(string.Format("tcp://localhost"));
            // Uris uri = new Uri(string.Format("mock://localhost:61616?transport.respondToMessages=false"));
            string             uri     = "tcp://${activemqhost}:61616?transport.useLogging=true";
            IConnectionFactory factory = new ConnectionFactory(NMSTestSupport.ReplaceEnvVar(uri));

            // ConnectionFactory factory = new ConnectionFactory(uri);
            using (IConnection connection = await factory.CreateConnectionAsync())
                using (ISession session = await connection.CreateSessionAsync())
                {
                    IDestination destination = await session.GetTopicAsync("Test");

                    using (IMessageProducer producer = await session.CreateProducerAsync(destination))
                    {
                        ITextMessage message = await session.CreateTextMessageAsync("Hello World");

                        message.NMSTimeToLive = TimeSpan.FromSeconds(175);
                        await producer.SendAsync(message);

                        // ITextMessage message2 = await session.CreateTextMessageAsync("Hello World");
                        // // message2.NMSTimeToLive = TimeSpan.FromSeconds(175);
                        // await producer.SendAsync(message2);
                    }
                }
        }
Esempio n. 4
0
        public async Task TestSendWhenLinkCreditIsZeroAndTimeout()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                IConnection connection = await EstablishConnectionAsync(testPeer, optionsString : "nms.sendTimeout=500");

                testPeer.ExpectBegin();

                ISession session = await connection.CreateSessionAsync(AcknowledgementMode.AutoAcknowledge);

                IQueue queue = await session.GetQueueAsync("myQueue");

                ITextMessage message = await session.CreateTextMessageAsync("text");

                // Expect the producer to attach. Don't send any credit so that the client will
                // block on a send and we can test our timeouts.
                testPeer.ExpectSenderAttachWithoutGrantingCredit();
                testPeer.ExpectClose();

                IMessageProducer producer = await session.CreateProducerAsync(queue);

                Assert.CatchAsync <Exception>(async() => await producer.SendAsync(message), "Send should time out.");

                await connection.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(1000);
            }
        }
Esempio n. 5
0
        public async Task TestNonDefaultPriorityProducesMessagesWithPriorityFieldAndSetsNMSPriority()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                IConnection connection = await EstablishConnectionAsync(testPeer);

                testPeer.ExpectBegin();
                testPeer.ExpectSenderAttach();

                ISession session = await connection.CreateSessionAsync(AcknowledgementMode.AutoAcknowledge);

                IQueue destination = await session.GetQueueAsync("myQueue");

                IMessageProducer producer = await session.CreateProducerAsync(destination);

                byte priority = 9;

                testPeer.ExpectTransfer(m => Assert.AreEqual(priority, m.Header.Priority));
                testPeer.ExpectClose();

                ITextMessage message = await session.CreateTextMessageAsync();

                Assert.AreEqual(MsgPriority.BelowNormal, message.NMSPriority);

                await producer.SendAsync(message, MsgDeliveryMode.Persistent, (MsgPriority)priority, NMSConstants.defaultTimeToLive);

                Assert.AreEqual((MsgPriority)priority, message.NMSPriority);

                await connection.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(1000);
            }
        }
Esempio n. 6
0
        public async Task TestMessagesAreProducedWithProperDefaultPriorityWhenNoPrioritySpecified()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                IConnection connection = await EstablishConnectionAsync(testPeer);

                testPeer.ExpectBegin();
                testPeer.ExpectSenderAttach();

                ISession session = await connection.CreateSessionAsync(AcknowledgementMode.AutoAcknowledge);

                IQueue destination = await session.GetQueueAsync("myQueue");

                IMessageProducer producer = await session.CreateProducerAsync(destination);

                byte priority = 4;

                testPeer.ExpectTransfer(m => Assert.AreEqual(priority, m.Header.Priority));
                testPeer.ExpectClose();

                ITextMessage message = await session.CreateTextMessageAsync();

                Assert.AreEqual(MsgPriority.BelowNormal, message.NMSPriority);

                await producer.SendAsync(message);

                Assert.AreEqual((MsgPriority)priority, message.NMSPriority);

                await connection.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(1000);
            }
        }
Esempio n. 7
0
        public async Task TestSendTimesOutWhenNoDispositionArrives()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                IConnection connection = await EstablishConnectionAsync(testPeer, optionsString : "nms.sendTimeout=500");

                testPeer.ExpectBegin();

                ISession session = await connection.CreateSessionAsync(AcknowledgementMode.AutoAcknowledge);

                IQueue queue = await session.GetQueueAsync("myQueue");

                ITextMessage message = await session.CreateTextMessageAsync("text");

                // Expect the producer to attach and grant it some credit, it should send
                // a transfer which we will not send any response for which should cause the
                // send operation to time out.
                testPeer.ExpectSenderAttach();
                testPeer.ExpectTransferButDoNotRespond(messageMatcher: Assert.NotNull);
                testPeer.ExpectClose();

                IMessageProducer producer = await session.CreateProducerAsync(queue);

                Assert.CatchAsync <Exception>(async() => await producer.SendAsync(message), "Send should time out.");

                await connection.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(1000);
            }
        }
Esempio n. 8
0
        public async Task TestSendWorksAfterConnectionStopped()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                IConnection connection = await EstablishConnectionAsync(testPeer);

                await connection.StartAsync();

                testPeer.ExpectBegin();
                testPeer.ExpectSenderAttach();

                ISession session = await connection.CreateSessionAsync(AcknowledgementMode.AutoAcknowledge);

                IQueue destination = await session.GetQueueAsync("myQueue");

                IMessageProducer producer = await session.CreateProducerAsync(destination);

                testPeer.ExpectTransfer(Assert.IsNotNull);

                await connection.StopAsync();

                await producer.SendAsync(await session.CreateMessageAsync());

                testPeer.ExpectDetach(expectClosed: true, sendResponse: true, replyClosed: true);
                testPeer.ExpectClose();

                await producer.CloseAsync();

                await connection.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(1000);
            }
        }
Esempio n. 9
0
        public async Task TestSendingMessageSetsNMSDestination()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                IConnection connection = await EstablishConnectionAsync(testPeer);

                testPeer.ExpectBegin();
                testPeer.ExpectSenderAttach();

                ISession session = await connection.CreateSessionAsync(AcknowledgementMode.AutoAcknowledge);

                IQueue destination = await session.GetQueueAsync("myQueue");

                IMessageProducer producer = await session.CreateProducerAsync(destination);

                string       text    = "myMessage";
                ITextMessage message = await session.CreateTextMessageAsync(text);

                testPeer.ExpectTransfer(m => Assert.AreEqual(text, (m.BodySection as AmqpValue).Value));
                testPeer.ExpectClose();

                Assert.IsNull(message.NMSDestination, "Should not yet have a NMSDestination");

                await producer.SendAsync(message);

                Assert.AreEqual(destination, message.NMSDestination, "Should have had NMSDestination set");

                await connection.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(1000);
            }
        }
Esempio n. 10
0
        public async Task TestSentTextMessageCanBeModified()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                IConnection connection = await base.EstablishConnectionAsync(testPeer);

                testPeer.ExpectBegin();
                testPeer.ExpectSenderAttach();

                ISession session = await connection.CreateSessionAsync(AcknowledgementMode.AutoAcknowledge);

                IQueue queue = await session.GetQueueAsync("myQueue");

                IMessageProducer producer = await session.CreateProducerAsync(queue);

                // Create and transfer a new message
                String text = "myMessage";
                testPeer.ExpectTransfer(x => Assert.AreEqual(text, (x.BodySection as AmqpValue).Value));
                testPeer.ExpectClose();

                ITextMessage message = await session.CreateTextMessageAsync(text);

                await producer.SendAsync(message);

                Assert.AreEqual(text, message.Text);
                message.Text = text + text;
                Assert.AreEqual(text + text, message.Text);

                await connection.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(1000);
            }
        }
Esempio n. 11
0
        public async Task TestDefaultDeliveryModeProducesDurableMessages()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                IConnection connection = await base.EstablishConnectionAsync(testPeer);

                testPeer.ExpectBegin();
                testPeer.ExpectSenderAttach();

                ISession session = await connection.CreateSessionAsync(AcknowledgementMode.AutoAcknowledge);

                IQueue queue = await session.GetQueueAsync("myQueue");

                IMessageProducer producer = await session.CreateProducerAsync(queue);

                // Create and transfer a new message
                testPeer.ExpectTransfer(message => Assert.IsTrue(message.Header.Durable));
                testPeer.ExpectClose();

                ITextMessage textMessage = await session.CreateTextMessageAsync();

                await producer.SendAsync(textMessage);

                Assert.AreEqual(MsgDeliveryMode.Persistent, textMessage.NMSDeliveryMode);

                await connection.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(1000);
            }
        }
Esempio n. 12
0
        public async Task TestNoCopyOnSend()
        {
            Uri uri = new Uri("mock://localhost:61616?connection.CopyMessageOnSend=false");

            ConnectionFactory factory = new ConnectionFactory(uri);

            using (IConnection connection = await factory.CreateConnectionAsync())
                using (ISession session = await connection.CreateSessionAsync())
                {
                    IDestination destination = await session.GetTopicAsync("Test");

                    using (IMessageProducer producer = await session.CreateProducerAsync(destination))
                    {
                        ITextMessage message = await session.CreateTextMessageAsync();

                        for (int i = 0; i < 10; ++i)
                        {
                            try
                            {
                                message.Properties["TribbleName"] = "Tribble" + i.ToString();
                                message.Text = "The Trouble with Tribbles - " + i.ToString();
                                await producer.SendAsync(message);
                            }
                            catch (MessageNotWriteableException)
                            {
                                Assert.Greater(i, 0);
                                Assert.Less(i, 10);
                            }
                        }
                    }
                }
        }
        public async Task TestProducerWorkWithAsyncAwait()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                IConnection connection = await base.EstablishConnectionAsync(testPeer);

                testPeer.ExpectBegin();
                testPeer.ExpectSenderAttach();

                ISession session = await connection.CreateSessionAsync(AcknowledgementMode.AutoAcknowledge);

                IQueue queue = await session.GetQueueAsync("myQueue");

                IMessageProducer producer = await session.CreateProducerAsync(queue);

                // Create and transfer a new message, explicitly setting the deliveryMode on the
                // message (which applications shouldn't) to NON_PERSISTENT and sending it to check
                // that the producer ignores this value and sends the message as PERSISTENT(/durable)
                testPeer.ExpectTransfer(message => Assert.IsTrue(message.Header.Durable));
                testPeer.ExpectClose();

                ITextMessage textMessage = await session.CreateTextMessageAsync();

                textMessage.NMSDeliveryMode = MsgDeliveryMode.NonPersistent;
                Assert.AreEqual(MsgDeliveryMode.NonPersistent, textMessage.NMSDeliveryMode);

                await producer.SendAsync(textMessage);

                Assert.AreEqual(MsgDeliveryMode.Persistent, textMessage.NMSDeliveryMode);

                await connection.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(1000);
            }
        }
Esempio n. 14
0
        public async Task ConsumeInTwoThreads()
        {
            ParameterizedThreadStart threadStart =
                delegate(object o)
            {
                IMessageConsumer consumer = (IMessageConsumer)o;
                IMessage         message  = consumer.Receive(TimeSpan.FromSeconds(2));
                Assert.IsNotNull(message);
            };

            using (IConnection connection = CreateConnection(TEST_CLIENT_ID))
            {
                await connection.StartAsync();

                using (ISession session = await connection.CreateSessionAsync(AcknowledgementMode.Transactional))
                {
                    IQueue queue = SessionUtil.GetDestination(session, DESTINATION_NAME) as IQueue;

                    // enqueue 2 messages
                    using (IMessageConsumer consumer = await session.CreateConsumerAsync(queue))
                        using (IMessageProducer producer = await session.CreateProducerAsync(queue))
                        {
                            producer.DeliveryMode = MsgDeliveryMode.Persistent;
                            await producer.SendAsync(producer.CreateMessage());

                            await producer.SendAsync(producer.CreateMessage());

                            await session.CommitAsync();

                            // receive first using a dedicated thread. This works
                            Thread thread = new Thread(threadStart);
                            thread.Start(consumer);
                            thread.Join();
                            await session.CommitAsync();

                            // receive second using main thread. This FAILS
                            IMessage message = await consumer.ReceiveAsync(TimeSpan.FromSeconds(2)); // throws System.Threading.AbandonedMutexException

                            Assert.IsNotNull(message);
                            await session.CommitAsync();
                        }
                }
            }
        }
Esempio n. 15
0
        public async Task TestBadSelectorDoesNotCloseConnection()
        {
            using (IConnection connection = CreateConnection(TEST_CLIENT_ID))
            {
                using (ISession sender = await connection.CreateSessionAsync(AcknowledgementMode.AutoAcknowledge))
                    using (ISession session = await connection.CreateSessionAsync(AcknowledgementMode.AutoAcknowledge))
                    {
                        IDestination destination = await sender.CreateTemporaryQueueAsync();

                        IMessageProducer producer = await sender.CreateProducerAsync(destination);

                        ITextMessage goodMsg = await sender.CreateTextMessageAsync("testGood");

                        await producer.SendAsync(goodMsg);

                        IMessageConsumer consumer = await session.CreateConsumerAsync(destination);

                        await connection.StartAsync();

                        Assert.NotNull(await consumer.ReceiveAsync(TimeSpan.FromMilliseconds(5000)));

                        try
                        {
                            ISession badListenerSession = await connection.CreateSessionAsync(AcknowledgementMode.AutoAcknowledge);

                            await badListenerSession.CreateConsumerAsync(destination, "badSelector;too");

                            Assert.Fail("Exception expected.");
                        }
                        catch (Exception e)
                        {
                            Tracer.DebugFormat("Caught Ex: {0}", e);
                        }

                        ITextMessage failMsg = await sender.CreateTextMessageAsync("testFail");

                        await producer.SendAsync(failMsg);

                        Assert.NotNull(await consumer.ReceiveAsync(TimeSpan.FromMilliseconds(5000)));
                    }
            }
        }
        public async Task PublishAsync(string aggregateType, object aggregateId, IDictionary <string, string> headers, IList <IDomainEvent> domainEvents)
        {
            var logContext = $"{nameof(PublishAsync)}, aggregateType='{aggregateType}', aggregateId='{aggregateId}' " +
                             $"with {headers.Count} headers and {domainEvents.Count} events";

            _logger.LogDebug($"+{logContext}");
            foreach (IDomainEvent domainEvent in domainEvents)
            {
                await _messageProducer.SendAsync(aggregateType,
                                                 MakeMessageForDomainEvent(aggregateType, aggregateId, headers, domainEvent,
                                                                           _eventTypeNamingStrategy));
            }
            _logger.LogDebug($"-{logContext}");
        }
Esempio n. 17
0
        public async Task TestAsyncDispatchExceptionRedelivers()
        {
            using (IConnection connection = CreateConnection(TEST_CLIENT_ID))
            {
                using (ISession session = await connection.CreateSessionAsync(AcknowledgementMode.AutoAcknowledge))
                {
                    IQueue queue = SessionUtil.GetDestination(session, DESTINATION_NAME) as IQueue;

                    using (IMessageProducer producer = await session.CreateProducerAsync(queue))
                    {
                        producer.DeliveryMode = MsgDeliveryMode.NonPersistent;
                        await producer.SendAsync(producer.CreateTextMessage("First"));

                        await producer.SendAsync(producer.CreateTextMessage("Second"));
                    }

                    using (IMessageConsumer consumer = await session.CreateConsumerAsync(queue))
                    {
                        consumer.Listener += OnTestAsynchRedliversMessage;

                        await connection.StartAsync();

                        if (LatchAwait(doneLatch, TimeSpan.FromSeconds(10)))
                        {
                            if (!String.IsNullOrEmpty(errorMessage))
                            {
                                Assert.Fail(errorMessage);
                            }
                        }
                        else
                        {
                            Assert.Fail("Timeout waiting for async message delivery to complete.");
                        }
                    }
                }
            }
        }
        public async Task <IActionResult> Create(User user)
        {
            var message = new UserCreatedMessage()
            {
                FirstName = user.FirstName,
                LastName  = user.LastName,
                UserName  = $"{user.FirstName}{user.LastName}"
            };

            await MessageProducer.SendAsync(message, "users.created");

            Console.WriteLine("Message sent: \n" + JsonSerializer.Serialize(message));

            return(Ok());
        }
Esempio n. 19
0
        private async Task DoSendingMessageWithDisableMessageIdHintTestImpl(bool existingId)
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                IConnection connection = await EstablishConnectionAsync(testPeer);

                testPeer.ExpectBegin();
                testPeer.ExpectSenderAttach();

                ISession session = await connection.CreateSessionAsync(AcknowledgementMode.AutoAcknowledge);

                IQueue destination = await session.GetQueueAsync("myQueue");

                IMessageProducer producer = await session.CreateProducerAsync(destination);

                string text = "myMessage";
                testPeer.ExpectTransfer(m =>
                {
                    Assert.IsTrue(m.Header.Durable);
                    Assert.IsNull(m.Properties.MessageId); // Check there is no message-id value;
                    Assert.AreEqual(text, (m.BodySection as AmqpValue).Value);
                });
                testPeer.ExpectClose();

                ITextMessage message = await session.CreateTextMessageAsync(text);

                Assert.IsNull(message.NMSMessageId, "NMSMessageId should not yet be set");

                if (existingId)
                {
                    string existingMessageId = "ID:this-should-be-overwritten-in-send";
                    message.NMSMessageId = existingMessageId;
                    Assert.AreEqual(existingMessageId, message.NMSMessageId, "NMSMessageId should now be se");
                }

                producer.DisableMessageID = true;

                await producer.SendAsync(message);

                Assert.IsNull(message.NMSMessageId, "NMSMessageID should be null");

                await connection.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }
        public async Task TestDeliveryDelayHasItsReflectionInAmqpAnnotations()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                // Determine current time
                TimeSpan deliveryDelay         = TimeSpan.FromMinutes(17);
                long     currentUnixEpochTime  = new DateTimeOffset(DateTime.UtcNow + deliveryDelay).ToUnixTimeMilliseconds();
                long     currentUnixEpochTime2 = new DateTimeOffset(DateTime.UtcNow + deliveryDelay + deliveryDelay).ToUnixTimeMilliseconds();

                IConnection connection = await base.EstablishConnectionAsync(testPeer,
                                                                             serverCapabilities : new Symbol[] { SymbolUtil.OPEN_CAPABILITY_DELAYED_DELIVERY, SymbolUtil.OPEN_CAPABILITY_SOLE_CONNECTION_FOR_CONTAINER });

                testPeer.ExpectBegin();
                testPeer.ExpectSenderAttach();


                ISession session = await connection.CreateSessionAsync(AcknowledgementMode.AutoAcknowledge);

                IQueue queue = await session.GetQueueAsync("myQueue");

                IMessageProducer producer = await session.CreateProducerAsync(queue);

                producer.DeliveryDelay = deliveryDelay;

                // Create and transfer a new message
                testPeer.ExpectTransfer(message =>
                {
                    Assert.GreaterOrEqual((long)message.MessageAnnotations[SymbolUtil.NMS_DELIVERY_TIME], currentUnixEpochTime);
                    Assert.Less((long)message.MessageAnnotations[SymbolUtil.NMS_DELIVERY_TIME], currentUnixEpochTime2);

                    Assert.IsTrue(message.Header.Durable);
                });
                testPeer.ExpectClose();

                ITextMessage textMessage = await session.CreateTextMessageAsync();

                await producer.SendAsync(textMessage);

                Assert.AreEqual(MsgDeliveryMode.Persistent, textMessage.NMSDeliveryMode);

                await connection.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(1000);
            }
        }
Esempio n. 21
0
        public async Task TestSendingMessageSetsNMSExpirationRelatedAbsoluteExpiryAndTtlFields()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                IConnection connection = await EstablishConnectionAsync(testPeer);

                testPeer.ExpectBegin();
                testPeer.ExpectSenderAttach();

                ISession session = await connection.CreateSessionAsync(AcknowledgementMode.AutoAcknowledge);

                IQueue destination = await session.GetQueueAsync("myQueue");

                IMessageProducer producer = await session.CreateProducerAsync(destination);

                uint     ttl             = 100_000;
                DateTime currentTime     = DateTime.UtcNow;
                DateTime expirationLower = currentTime + TimeSpan.FromMilliseconds(ttl);
                DateTime expirationUpper = currentTime + TimeSpan.FromMilliseconds(ttl) + TimeSpan.FromMilliseconds(5000);

                // Create matcher to expect the absolute-expiry-time field of the properties section to
                // be set to a value greater than 'now'+ttl, within a delta.
                string text = "myMessage";
                testPeer.ExpectTransfer(m =>
                {
                    Assert.IsTrue(m.Header.Durable);
                    Assert.AreEqual(ttl, m.Header.Ttl);
                    Assert.That(m.Properties.AbsoluteExpiryTime.Ticks, Is.GreaterThanOrEqualTo(expirationLower.Ticks).Within(TICKS_PER_MILLISECOND));
                    Assert.That(m.Properties.AbsoluteExpiryTime.Ticks, Is.LessThanOrEqualTo(expirationUpper.Ticks).Within(TICKS_PER_MILLISECOND));
                    Assert.AreEqual(text, (m.BodySection as AmqpValue).Value);
                });

                ITextMessage message = await session.CreateTextMessageAsync(text);

                await producer.SendAsync(message, NMSConstants.defaultDeliveryMode, NMSConstants.defaultPriority, TimeSpan.FromMilliseconds(ttl));

                testPeer.WaitForAllMatchersToComplete(1000);

                testPeer.ExpectClose();
                await connection.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(1000);
            }
        }
Esempio n. 22
0
        public async Task TestSendingMessageSetsNMSMessageId()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                IConnection connection = await EstablishConnectionAsync(testPeer);

                testPeer.ExpectBegin();
                testPeer.ExpectSenderAttach();

                ISession session = await connection.CreateSessionAsync(AcknowledgementMode.AutoAcknowledge);

                IQueue destination = await session.GetQueueAsync("myQueue");

                IMessageProducer producer = await session.CreateProducerAsync(destination);

                string text            = "myMessage";
                string actualMessageId = null;
                testPeer.ExpectTransfer(m =>
                {
                    Assert.IsTrue(m.Header.Durable);
                    Assert.IsNotEmpty(m.Properties.MessageId);
                    actualMessageId = m.Properties.MessageId;
                });
                testPeer.ExpectClose();

                ITextMessage message = await session.CreateTextMessageAsync(text);

                Assert.IsNull(message.NMSMessageId, "NMSMessageId should not yet be set");

                await producer.SendAsync(message);

                Assert.IsNotNull(message.NMSMessageId);
                Assert.IsNotEmpty(message.NMSMessageId, "NMSMessageId should be set");
                Assert.IsTrue(message.NMSMessageId.StartsWith("ID:"), "MMS 'ID:' prefix not found");

                await connection.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(1000);
                // Get the value that was actually transmitted/received, verify it is a string, compare to what we have locally
                Assert.AreEqual(message.NMSMessageId, actualMessageId, "Expected NMSMessageId value to be present in AMQP message");
            }
        }
Esempio n. 23
0
        public async Task TestProducerSendWithTimeout()
        {
            int timeout = 1500;
            Uri uri     = new Uri(string.Format("mock://localhost:61616?connection.RequestTimeout={0}&transport.respondToMessages=false", timeout));

            ConnectionFactory factory = new ConnectionFactory(uri);

            using (IConnection connection = await factory.CreateConnectionAsync())
                using (ISession session = await connection.CreateSessionAsync())
                {
                    IDestination destination = await session.GetTopicAsync("Test");

                    using (IMessageProducer producer = await session.CreateProducerAsync(destination))
                    {
                        ITextMessage message = await session.CreateTextMessageAsync("Hello World");

                        for (int i = 0; i < 10; ++i)
                        {
                            DateTime start = DateTime.Now;

                            try
                            {
                                await producer.SendAsync(message);

                                Assert.Fail("Expected a RequestTimedOutException");
                            }
                            catch (RequestTimedOutException)
                            {
                            }

                            TimeSpan elapsed = DateTime.Now - start;
                            // Make sure we timed out.
                            Assert.GreaterOrEqual((int)elapsed.TotalMilliseconds, timeout - 75, "Did not reach timeout limit.");
                        }
                    }
                }
        }
Esempio n. 24
0
        public async Task TestSendingMessageNonPersistentSetsBatchableFalse()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                IConnection connection = await EstablishConnectionAsync(testPeer);

                await connection.StartAsync();

                testPeer.ExpectBegin();
                testPeer.ExpectSenderAttach();

                ISession session = await connection.CreateSessionAsync(AcknowledgementMode.AutoAcknowledge);

                IQueue destination = await session.GetQueueAsync("myQueue");

                IMessageProducer producer = await session.CreateProducerAsync(destination);

                testPeer.ExpectTransfer(messageMatcher: Assert.IsNotNull,
                                        stateMatcher: Assert.IsNull,
                                        settled: false,
                                        sendResponseDisposition: true,
                                        responseState: new Accepted(),
                                        responseSettled: true,
                                        batchable: false);

                IMessage message = await session.CreateMessageAsync();

                await producer.SendAsync(message : message, deliveryMode : MsgDeliveryMode.NonPersistent, MsgPriority.Normal, NMSConstants.defaultTimeToLive);

                testPeer.WaitForAllMatchersToComplete(1000);

                testPeer.ExpectClose();
                await connection.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(1000);
            }
        }
        public void TestSentAsyncIsAsynchronous()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                IConnection connection = base.EstablishConnection(testPeer);
                testPeer.ExpectBegin();
                testPeer.ExpectSenderAttach();

                ISession         session  = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
                IQueue           queue    = session.GetQueue("myQueue");
                IMessageProducer producer = session.CreateProducer(queue);

                // Create and transfer a new message
                String text = "myMessage";
                testPeer.ExpectTransfer(messageMatcher: m => Assert.AreEqual(text, (m.BodySection as AmqpValue).Value),
                                        settled: false,
                                        sendResponseDisposition: true,
                                        responseState: new Accepted(),
                                        responseSettled: true,
                                        stateMatcher: Assert.IsNull,
                                        dispositionDelay: 10); // 10ms should be enough
                testPeer.ExpectClose();

                ITextMessage message  = session.CreateTextMessage(text);
                var          sendTask = producer.SendAsync(message);
                // Instantly check if its not completed yet, we want async, so it should not be completed right after
                Assert.AreEqual(false, sendTask.IsCompleted);

                // And now wait for task to complete
                sendTask.Wait(20_000);

                connection.Close();

                testPeer.WaitForAllMatchersToComplete(1000);
            }
        }
Esempio n. 26
0
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="model">消息模型 按照<see cref="ISerializer"/>规则序列化</param>
        /// <param name="exchange">交换机</param>
        /// <param name="routingKey"></param>
        /// <param name="header">消息头部参数<see cref="IBasicProperties.Headers"/> 或者 <see cref="Generic.Headers"/></param>
        /// <returns></returns>
        public Task <ProducerResult> SendMessageAsync <T>(T model, string exchange, string routingKey, IDictionary <string, string> header = null) where T : class, new()
        {
            IDictionary <string, string> innerHeader = GetMessageHeader(exchange, routingKey, header);

            return(_messageProducer.SendAsync(new Message <T>(innerHeader, model)));
        }
Esempio n. 27
0
        public async Task TestReceiveIgnoreExpirationMessage(
            [Values(AcknowledgementMode.AutoAcknowledge, AcknowledgementMode.ClientAcknowledge,
                    AcknowledgementMode.DupsOkAcknowledge, AcknowledgementMode.Transactional)]
            AcknowledgementMode ackMode,
            [Values(MsgDeliveryMode.NonPersistent, MsgDeliveryMode.Persistent)]
            MsgDeliveryMode deliveryMode,
            [Values(ExpirationOptions.DEFAULT, ExpirationOptions.IGNORE, ExpirationOptions.DO_NOT_IGNORE)]
            ExpirationOptions expirationOption)
        {
            using (IConnection connection = CreateConnection(TEST_CLIENT_ID))
            {
                await connection.StartAsync();

                using (Session session = await connection.CreateSessionAsync(ackMode) as Session)
                {
                    string destinationName = DESTINATION_NAME;

                    if (ExpirationOptions.IGNORE == expirationOption)
                    {
                        destinationName += "?consumer.nms.ignoreExpiration=true";
                    }
                    else if (ExpirationOptions.DO_NOT_IGNORE == expirationOption)
                    {
                        destinationName += "?consumer.nms.ignoreExpiration=false";
                    }

                    try
                    {
                        IDestination destination = SessionUtil.GetDestination(session, destinationName);

                        using (IMessageConsumer consumer = await session.CreateConsumerAsync(destination))
                            using (IMessageProducer producer = await session.CreateProducerAsync(destination))
                            {
                                producer.DeliveryMode = deliveryMode;

                                string msgText = string.Format("ExpiredMessage: {0}", Guid.NewGuid().ToString());

                                ActiveMQTextMessage msg = await session.CreateTextMessageAsync(msgText) as ActiveMQTextMessage;

                                // Give it two seconds to live.
                                msg.NMSTimeToLive = TimeSpan.FromMilliseconds(2000);

                                await producer.SendAsync(msg);

                                if (AcknowledgementMode.Transactional == ackMode)
                                {
                                    await session.CommitAsync();
                                }

                                // Wait for four seconds before processing it.  The broker will have sent it to our local
                                // client dispatch queue, but we won't attempt to process the message until it has had
                                // a chance to expire within our internal queue system.
                                Thread.Sleep(4000);

                                ActiveMQTextMessage rcvMsg = consumer.ReceiveNoWait() as ActiveMQTextMessage;

                                if (ExpirationOptions.IGNORE == expirationOption)
                                {
                                    Assert.IsNotNull(rcvMsg, "Did not receive expired message.");
                                    await rcvMsg.AcknowledgeAsync();

                                    Assert.AreEqual(msgText, rcvMsg.Text, "Message text does not match.");
                                    Assert.IsTrue(rcvMsg.IsExpired());

                                    if (AcknowledgementMode.Transactional == ackMode)
                                    {
                                        await session.CommitAsync();
                                    }
                                }
                                else
                                {
                                    // Should not receive a message.
                                    Assert.IsNull(rcvMsg, "Received an expired message!");
                                }

                                await consumer.CloseAsync();

                                await producer.CloseAsync();
                            }
                    }
                    finally
                    {
                        try
                        {
                            // Ensure that Session resources on the Broker release transacted Consumers.
                            await session.CloseAsync();

                            // Give the Broker some time to remove the subscriptions.
                            Thread.Sleep(2000);
                            SessionUtil.DeleteDestination(session, destinationName);
                        }
                        catch
                        {
                        }
                    }
                }
            }
        }
Esempio n. 28
0
        private async Task DoSendingMessageNonPersistentTestImpl(bool anonymousProducer, bool setPriority, bool setOnProducer)
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                //Add capability to indicate support for ANONYMOUS-RELAY
                Symbol[]    serverCapabilities = { SymbolUtil.OPEN_CAPABILITY_ANONYMOUS_RELAY };
                IConnection connection         = await EstablishConnectionAsync(testPeer, serverCapabilities : serverCapabilities);

                testPeer.ExpectBegin();

                string          queueName     = "myQueue";
                Action <object> targetMatcher = t =>
                {
                    var target = t as Target;
                    Assert.IsNotNull(target);
                    if (anonymousProducer)
                    {
                        Assert.IsNull(target.Address);
                    }
                    else
                    {
                        Assert.AreEqual(queueName, target.Address);
                    }
                };


                testPeer.ExpectSenderAttach(targetMatcher: targetMatcher, sourceMatcher: Assert.NotNull, senderSettled: false);

                ISession session = await connection.CreateSessionAsync(AcknowledgementMode.AutoAcknowledge);

                IQueue queue = await session.GetQueueAsync(queueName);

                IMessageProducer producer = null;
                if (anonymousProducer)
                {
                    producer = await session.CreateProducerAsync();
                }
                else
                {
                    producer = await session.CreateProducerAsync(queue);
                }

                byte   priority = 5;
                String text     = "myMessage";
                testPeer.ExpectTransfer(messageMatcher: message =>
                {
                    if (setPriority)
                    {
                        Assert.IsFalse(message.Header.Durable);
                        Assert.AreEqual(5, message.Header.Priority);
                    }

                    Assert.AreEqual(text, (message.BodySection as AmqpValue).Value);
                }, stateMatcher: Assert.IsNull,
                                        settled: false,
                                        sendResponseDisposition: true,
                                        responseState: new Accepted(),
                                        responseSettled: true);

                ITextMessage textMessage = await session.CreateTextMessageAsync(text);

                if (setOnProducer)
                {
                    producer.DeliveryMode = MsgDeliveryMode.NonPersistent;
                    if (setPriority)
                    {
                        producer.Priority = (MsgPriority)5;
                    }

                    if (anonymousProducer)
                    {
                        await producer.SendAsync(queue, textMessage);
                    }
                    else
                    {
                        await producer.SendAsync(textMessage);
                    }
                }
                else
                {
                    if (anonymousProducer)
                    {
                        await producer.SendAsync(destination : queue,
                                                 message : textMessage,
                                                 deliveryMode : MsgDeliveryMode.NonPersistent,
                                                 priority : setPriority?(MsgPriority)priority : NMSConstants.defaultPriority,
                                                 timeToLive : NMSConstants.defaultTimeToLive);
                    }
                    else
                    {
                        await producer.SendAsync(message : textMessage,
                                                 deliveryMode : MsgDeliveryMode.NonPersistent,
                                                 priority : setPriority?(MsgPriority)priority : NMSConstants.defaultPriority,
                                                 timeToLive : NMSConstants.defaultTimeToLive);
                    }
                }

                Assert.AreEqual(MsgDeliveryMode.NonPersistent, textMessage.NMSDeliveryMode, "Should have NonPersistent delivery mode set");

                testPeer.WaitForAllMatchersToComplete(1000);

                testPeer.ExpectClose();
                await connection.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(1000);
            }
        }