示例#1
0
        public void MessageExpirationWorks()
        {
            // arrange
            var timeToBeReceived = 2.Seconds().ToString();

            const string recipientInputQueueName = "test.expiration.recipient";
            const string senderInputQueueName    = "test.expiration.sender";

            using (var recipientQueue = new RabbitMqMessageQueue(ConnectionString, recipientInputQueueName))
                using (var senderQueue = new RabbitMqMessageQueue(ConnectionString, senderInputQueueName))
                {
                    senderQueue.Send(recipientInputQueueName,
                                     serializer.Serialize(new Message
                    {
                        Messages = new object[] { "HELLO WORLD!" },
                        Headers  =
                            new Dictionary <string, object>
                        {
                            {
                                Headers.TimeToBeReceived,
                                timeToBeReceived
                            }
                        },
                    }),
                                     new NoTransaction());

                    // act
                    Thread.Sleep(2.Seconds() + 1.Seconds());

                    // assert
                    var receivedTransportMessage = recipientQueue.ReceiveMessage(new NoTransaction());
                    Assert.That(receivedTransportMessage, Is.Null);
                }
        }
 protected override void DoSetUp()
 {
     using (var queue = new RabbitMqMessageQueue(ConnectionString, InputQueueName))
     {
         queue.PurgeInputQueue();
     }
 }
示例#3
0
        public void TransportLevelMessageIdIsPreserved()
        {
            const string recipientInputQueueName = "test.tlid.recipient";
            const string senderInputQueueName    = "test.tlid.sender";

            using (var recipientQueue = new RabbitMqMessageQueue(ConnectionString, recipientInputQueueName))
                using (var senderQueue = new RabbitMqMessageQueue(ConnectionString, senderInputQueueName))
                {
                    var id = Guid.NewGuid();
                    senderQueue.Send(recipientInputQueueName,
                                     serializer.Serialize(new Message
                    {
                        Messages = new object[] { "HELLO WORLD!" },
                        Headers  =
                            new Dictionary <string, object> {
                            { Headers.MessageId, id.ToString() }
                        },
                    }),
                                     new NoTransaction());

                    // act
                    Thread.Sleep(2.Seconds() + 1.Seconds());

                    // assert
                    var receivedTransportMessage = recipientQueue.ReceiveMessage(new NoTransaction());
                    Assert.That(receivedTransportMessage, Is.Not.Null);
                    Assert.That(receivedTransportMessage.Headers, Is.Not.Null);
                    Assert.That(receivedTransportMessage.Headers.ContainsKey(Headers.MessageId), Is.True);
                    Assert.That(receivedTransportMessage.Headers[Headers.MessageId], Is.EqualTo(id.ToString()));
                }
        }
示例#4
0
        public void AutomatiallyCreatesRecipientQueue()
        {
            // arrange
            const string senderInputQueue    = "test.autocreate.sender";
            const string recipientInputQueue = "test.autocreate.recipient";
            const string someText            = "whoa! as if by magic!";

            // ensure recipient queue does not exist
            DeleteQueue(senderInputQueue);
            DeleteQueue(recipientInputQueue);

            using (var sender = new RabbitMqMessageQueue(ConnectionString, senderInputQueue))
            {
                // act
                sender.Send(recipientInputQueue, new TransportMessageToSend
                {
                    Body = Encoding.GetBytes(someText)
                }, new NoTransaction());
            }

            using (var recipient = new RabbitMqMessageQueue(ConnectionString, recipientInputQueue))
            {
                // assert
                var receivedTransportMessage = recipient.ReceiveMessage(new NoTransaction());
                receivedTransportMessage.ShouldNotBe(null);
                Encoding.GetString(receivedTransportMessage.Body).ShouldBe(someText);
            }
        }
        public Tuple <ISendMessages, IReceiveMessages> GetQueue(string inputQueueName)
        {
            var rabbitMqMessageQueue = new RabbitMqMessageQueue(RabbitMqFixtureBase.ConnectionString, inputQueueName, "error").PurgeInputQueue();

            disposables.Add(rabbitMqMessageQueue);
            return(new Tuple <ISendMessages, IReceiveMessages>(rabbitMqMessageQueue, rabbitMqMessageQueue));
        }
示例#6
0
        public void CanCreateAutoDeleteQueue()
        {
            const string queueName = "test.autodelete.input";

            DeleteQueue(queueName);

            // arrange
            var  existedBeforeInstatiation = QueueExists(queueName);
            bool existedWhileInstantiatedAndInsideTx;
            bool existedWhileInstantiatedAndOutsideOfTx;

            // act
            using (var queue = new RabbitMqMessageQueue(ConnectionString, queueName).AutoDeleteInputQueue())
            {
                using (var scope = new TransactionScope())
                {
                    using (var txBomkarl = new TxBomkarl())
                    {
                        var willBeNull = queue.ReceiveMessage(txBomkarl);

                        existedWhileInstantiatedAndInsideTx = QueueExists(queueName);
                    }

                    existedWhileInstantiatedAndOutsideOfTx = QueueExists(queueName);
                }
            }

            var existedAfterDisposal = QueueExists(queueName);

            // assert
            existedBeforeInstatiation.ShouldBe(false);
            existedWhileInstantiatedAndInsideTx.ShouldBe(true);
            existedWhileInstantiatedAndOutsideOfTx.ShouldBe(true);
            existedAfterDisposal.ShouldBe(false);
        }
示例#7
0
        RabbitMqMessageQueue GetQueue(string queueName, bool removeExiting = false, bool oneExchangePerType = false, string inputExchange = null)
        {
            if (removeExiting)
            {
                DeleteQueue(queueName);
            }
            if (removeExiting && inputExchange != null)
            {
                DeleteExchange(inputExchange);
            }

            queuesToDelete.Add(queueName);
            var queue = new RabbitMqMessageQueue(ConnectionString, queueName);

            if (oneExchangePerType)
            {
                queue.UseExchange(null);
            }
            if (inputExchange != null)
            {
                queue.UseExchangeAsInputAddress(inputExchange);
            }
            DisposableTracker.TrackDisposable(queue);
            return(queue.PurgeInputQueue());
        }
示例#8
0
        public void CanSendToQueueWithEmptyExchangeAfterAtSign()
        {
            const string recipientInputQueueName = "test.atsimbol.recipient@";
            const string senderInputQueueName    = "test.atsimbol.sender";

            using (var recipientQueue = new RabbitMqMessageQueue(ConnectionString, recipientInputQueueName))
                using (var senderQueue = new RabbitMqMessageQueue(ConnectionString, senderInputQueueName))
                {
                    recipientQueue.PurgeInputQueue();
                    senderQueue.PurgeInputQueue();

                    var id = Guid.NewGuid();
                    senderQueue.Send(recipientInputQueueName,
                                     serializer.Serialize(new Message
                    {
                        Messages = new object[] { "HELLO WORLD!" },
                        Headers  =
                            new Dictionary <string, object> {
                            { Headers.MessageId, id.ToString() }
                        },
                    }),
                                     new NoTransaction());

                    // act
                    Thread.Sleep(2.Seconds() + 1.Seconds());

                    // assert
                    var receivedTransportMessage = recipientQueue.ReceiveMessage(new NoTransaction());
                    Assert.That(receivedTransportMessage, Is.Not.Null);
                }
        }
        RabbitMqMessageQueue GetQueue(string queueName)
        {
            var queue = new RabbitMqMessageQueue(ConnectionString, queueName, queueName + ".error");

            toDispose.Add(queue);
            return(queue.PurgeInputQueue());
        }
        public void ItHasBeenFixed()
        {
            using (var adapter = new BuiltinContainerAdapter())
            {
                adapter.Handle <string>(s =>
                {
                    throw new ApplicationException("Will trigger that the message gets moved to the error queue");
                });

                Configure.With(adapter)
                .Transport(t => t.UseRabbitMq(ConnectionString, "test.input", "test.error")
                           .UseExchange("AlternativeExchange"))
                .CreateBus()
                .Start();

                adapter.Bus.SendLocal("hello there!!!");

                // wait until we're sure
                Thread.Sleep(2.Seconds());

                using (var errorQueue = new RabbitMqMessageQueue(ConnectionString, "test.error"))
                {
                    var serializer = new JsonMessageSerializer();
                    var receivedTransportMessage = errorQueue.ReceiveMessage(new NoTransaction());
                    receivedTransportMessage.ShouldNotBe(null);

                    var errorMessage = serializer.Deserialize(receivedTransportMessage);
                    errorMessage.Messages.Length.ShouldBe(1);
                    errorMessage.Messages[0].ShouldBeOfType <string>();
                    ((string)errorMessage.Messages[0]).ShouldBe("hello there!!!");
                }
            }
        }
示例#11
0
        public void CanGeneratePrettyEventNames()
        {
            var queue = new RabbitMqMessageQueue(ConnectionString, "test.eventnames");

            var eventsAndExpectedEventNames =
                new List <Tuple <Type, string> >
            {
                Tuple.Create(typeof(string), "System.String"),
                Tuple.Create(typeof(List <string>), "System.Collections.Generic.List<System.String>"),
                Tuple.Create(typeof(List <Tuple <string, int, int> >), "System.Collections.Generic.List<System.Tuple<System.String, System.Int32, System.Int32>>"),
            };

            var results = AssertEventNames(queue, eventsAndExpectedEventNames);

            if (results.Any(r => r.Item1))
            {
                Console.WriteLine(@"The following event types were fine:

{0}", string.Join(Environment.NewLine, results.Where(r => r.Item1).Select(t => string.Format(@"  {0}:
    got : {1}
", t.Item2, t.Item3))));
            }

            if (results.Any(r => !r.Item1))
            {
                Assert.Fail(@"Did not get the expected results for the following event types:

{0}", string.Join(Environment.NewLine, results.Where(r => !r.Item1).Select(t => string.Format(@"  {0}:
    got      : {1}
    expected : {2}
", t.Item2, t.Item3, t.Item4))));
            }
        }
示例#12
0
        RabbitMqMessageQueue GetQueue(string queueName)
        {
            queuesToDelete.Add(queueName);
            var queue = new RabbitMqMessageQueue(ConnectionString, queueName);

            toDispose.Add(queue);
            return(queue.PurgeInputQueue());
        }
示例#13
0
        RabbitMqMessageQueue GetQueue(string queueName)
        {
            var queue = new RabbitMqMessageQueue(RabbitMqFixtureBase.ConnectionString, queueName, queueName + ".error");

            queue.PurgeInputQueue();
            disposables.Add(queue);
            return(queue);
        }
示例#14
0
 public RabbitMqTestIn()
 {
     rmq = new RabbitMqMessageQueue(new DistributedMQConfig()
     {
         ServerAddress = "测试地址",
         Topic         = "testDcpTopic",
         ProducerID    = "testDcpProductId",
         ConsumerID    = "testConsumerId"
     });
 }
示例#15
0
        public void IfQueueNameHasAtSimbolItIsCreatedCorrectly()
        {
            const string recipientInputQueueName = "test.AtSimbol@";

            queuesToDelete.Add(recipientInputQueueName);

            var recipientQueue = new RabbitMqMessageQueue(ConnectionString, recipientInputQueueName);

            recipientQueue.Initialize();

            DeclareQueue(recipientInputQueueName, passive: true).ShouldBe(false);
            DeclareQueue(recipientInputQueueName.TrimEnd('@'), passive: true).ShouldBe(true);
        }
示例#16
0
        protected RebusBus CreateBus(string inputQueueName, IActivateHandlers handlerActivator)
        {
            var rabbitMqMessageQueue = new RabbitMqMessageQueue(ConnectionString, inputQueueName, inputQueueName + ".error").PurgeInputQueue();

            var bus = new RebusBus(handlerActivator, rabbitMqMessageQueue, rabbitMqMessageQueue,
                                   new InMemorySubscriptionStorage(), new InMemorySagaPersister(), this,
                                   new JsonMessageSerializer(), new TrivialPipelineInspector(),
                                   new ErrorTracker(inputQueueName + ".error"));

            toDispose.Add(bus);
            toDispose.Add(rabbitMqMessageQueue);

            return(bus);
        }
示例#17
0
        public void RabbitTransportDoesNotChokeOnMessagesContainingComplexHeaders()
        {
            // arrange
            const string recipientInputQueue = "test.roundtripping.receiver";
            const string someText            = "whoohaa!";

            DeleteQueue(recipientInputQueue);

            // ensure recipient queue is created...
            using (var recipient = new RabbitMqMessageQueue(ConnectionString, recipientInputQueue))
            {
                // force creation of the queue
                recipient.ReceiveMessage(new NoTransaction());

                // act
                // send a message with a complex header
                using (var connection = new ConnectionFactory {
                    Uri = ConnectionString
                }.CreateConnection())
                    using (var model = connection.CreateModel())
                    {
                        var props = model.CreateBasicProperties();
                        props.Headers = new Hashtable
                        {
                            {
                                "someKey", new Hashtable
                                {
                                    { "someContainedKey", "someContainedValue" },
                                    { "anotherContainedKey", "anotherContainedValue" },
                                }
                            }
                        };

                        model.BasicPublish(recipient.ExchangeName,
                                           recipientInputQueue,
                                           props,
                                           Encoding.GetBytes(someText));
                    }

                Thread.Sleep(2.Seconds());

                // assert
                var receivedTransportMessage = recipient.ReceiveMessage(new NoTransaction());
                receivedTransportMessage.ShouldNotBe(null);
                Encoding.GetString(receivedTransportMessage.Body).ShouldBe(someText);
            }

            // assert
        }
示例#18
0
        protected override void DoSetUp()
        {
            adapter = TrackDisposable(new BuiltinContainerAdapter());

            Configure.With(adapter)
                .Transport(t => t.UseRabbitMq(RabbitMqFixtureBase.ConnectionString, InputQueueName, "error"))
                .Behavior(b => b.EnableMessageAudit(AuditQueueName))
                .CreateBus()
                .Start(1);

            RabbitMqFixtureBase.DeleteQueue(AuditQueueName);

            // make sure the receiver is in place at this point, ensuring that bindings'n'all are in place...
            auditQueueReceiver = TrackDisposable(new RabbitMqMessageQueue(RabbitMqFixtureBase.ConnectionString, AuditQueueName));
            auditQueueReceiver.Initialize();
        }
示例#19
0
        List <Tuple <bool, Type, string, string> > AssertEventNames(RabbitMqMessageQueue queue, IEnumerable <Tuple <Type, string> > eventsAndExpectedEventNames)
        {
            return(eventsAndExpectedEventNames
                   .Select(t =>
            {
                var eventType = t.Item1;
                var expectedEventName = t.Item2;

                var eventName = queue.GetEventName(eventType);

                return eventName == expectedEventName
                                   ? Tuple.Create(true, eventType, eventName, expectedEventName)
                                   : Tuple.Create(false, eventType, eventName, expectedEventName);
            })
                   .ToList());
        }
示例#20
0
        static List <ReceivedTransportMessage> GetAllMessages(RabbitMqMessageQueue recipient)
        {
            var timesNullReceived         = 0;
            var receivedTransportMessages = new List <ReceivedTransportMessage>();

            do
            {
                var msg = recipient.ReceiveMessage(new NoTransaction());
                if (msg == null)
                {
                    timesNullReceived++;
                    continue;
                }
                receivedTransportMessages.Add(msg);
            } while (timesNullReceived < 5);
            return(receivedTransportMessages);
        }
示例#21
0
        protected RebusBus CreateBus(string inputQueueName, IActivateHandlers handlerActivator)
        {
            queuesToDelete.Add(inputQueueName);
            queuesToDelete.Add(inputQueueName + ".error");


            var bus = Configure.With(new FakeContainerAdapter(handlerActivator))
                      .Transport(x => x.UseRabbitMq(ConnectionString, inputQueueName, inputQueueName + ".error"))
                      .CreateBus() as RebusBus;

            var rabbitMqMessageQueue = new RabbitMqMessageQueue(ConnectionString, inputQueueName).PurgeInputQueue();

            DisposableTracker.TrackDisposable(rabbitMqMessageQueue);
            DisposableTracker.TrackDisposable(bus);

            return(bus);
        }
示例#22
0
        static void Main(string[] args)
        {
            try
            {
                RabbitMqMessageQueue.Init();

                RabbitMqMessageQueue.Subscribe("MyQueue", async x =>
                {
                    Console.WriteLine($"Received message {x}");
                    await SlackHelper.SendSlackMessage(x);
                });

                Console.WriteLine("Waiting for messages...");
                Thread.Sleep(Timeout.Infinite);
            }
            finally
            {
                RabbitMqMessageQueue.Cleanup();
            }
        }
示例#23
0
        public void TestPerformanceOfPrettyEventNameGeneration(int count)
        {
            var queue      = new RabbitMqMessageQueue(ConnectionString, "test.eventnames");
            var eventTypes = new List <Type>
            {
                typeof(string),
                typeof(List <string>),
                typeof(List <Tuple <string, int, int> >),
                typeof(Tuple <List <Tuple <string, int, int, Tuple <string, int, Tuple <string, int, Tuple <string, int, Tuple <string, int, int> > > > > > >),
                typeof(Tuple <Tuple <List <Tuple <string, int, int, Tuple <string, int, Tuple <string, int, Tuple <string, int, Tuple <string, int, int> > > > > >,
                                     Tuple <List <Tuple <string, int, int, Tuple <string, int, Tuple <string, int, Tuple <string, int, Tuple <string, int, int> > > > > >,
                                            Tuple <List <Tuple <string, int, int, Tuple <string, int, Tuple <string, int, Tuple <string, int, Tuple <string, int, int> > > > > >,
                                                   Tuple <List <Tuple <string, int, int, Tuple <string, int, Tuple <string, int, Tuple <string, int, Tuple <string, int, int> > > > > > > > > > >),
            };

            var elapsed = eventTypes.Select(t =>
            {
                var stopwatch = Stopwatch.StartNew();
                count.Times(() => queue.GetEventName(t));
                return(Tuple.Create(queue.GetEventName(t), stopwatch.Elapsed));
            });

            Console.WriteLine(string.Join(Environment.NewLine, elapsed.Select(t => string.Format(@"    {0:0.0}   {1}", t.Item2.TotalSeconds, t.Item1))));
        }
示例#24
0
        static void Run(Parameters parameters)
        {
            if (string.IsNullOrWhiteSpace(parameters.ErrorQueueName))
            {
                throw new NiceException("Please specify the name of an error queue");
            }
            if (string.IsNullOrWhiteSpace(parameters.Host))
            {
                throw new NiceException("Please specify the hostname");
            }

            using (var rabbitMqMessageQueue = new RabbitMqMessageQueue(parameters.Host, parameters.ErrorQueueName))
            {
                using (var tx = new TransactionScope())
                {
                    var transactionContext = new AmbientTransactionContext();

                    var allTheMessages = GetAllTheMessages(rabbitMqMessageQueue, transactionContext);

                    foreach (var message in allTheMessages)
                    {
                        var transportMessageToSend = message.ToForwardableMessage();
                        try
                        {
                            if (!transportMessageToSend.Headers.ContainsKey(Headers.SourceQueue))
                            {
                                throw new NiceException("Message {0} does not have a source queue header - it will be moved back to the input queue",
                                                        message.Id);
                            }

                            var sourceQueue = (string)transportMessageToSend.Headers[Headers.SourceQueue];

                            if (parameters.AutoMoveAllMessages.GetValueOrDefault())
                            {
                                rabbitMqMessageQueue.Send(sourceQueue, transportMessageToSend, transactionContext);

                                Print("Moved {0} to {1}", message.Id, sourceQueue);
                            }
                            else
                            {
                                var answer = PromptChar(new[] { 'y', 'n' }, "Would you like to move {0} to {1}? (y/n)",
                                                        message.Id, sourceQueue);

                                if (answer == 'y')
                                {
                                    rabbitMqMessageQueue.Send(sourceQueue, transportMessageToSend, transactionContext);

                                    Print("Moved {0} to {1}", message.Id, sourceQueue);
                                }
                                else
                                {
                                    rabbitMqMessageQueue.Send(rabbitMqMessageQueue.InputQueueAddress,
                                                              transportMessageToSend,
                                                              transactionContext);

                                    Print("Moved {0} to {1}", message.Id, rabbitMqMessageQueue.InputQueueAddress);
                                }
                            }
                        }
                        catch (NiceException e)
                        {
                            Print(e.Message);

                            rabbitMqMessageQueue.Send(rabbitMqMessageQueue.InputQueueAddress,
                                                      transportMessageToSend,
                                                      transactionContext);
                        }
                    }

                    if (parameters.DryRun.GetValueOrDefault())
                    {
                        Print("Aborting queue transaction");
                        return;
                    }

                    if (!parameters.Interactive)
                    {
                        tx.Complete();
                        return;
                    }

                    var commitAnswer = PromptChar(new[] { 'y', 'n' }, "Would you like to commit the queue transaction?");

                    if (commitAnswer == 'y')
                    {
                        Print("Committing queue transaction");

                        tx.Complete();
                        return;
                    }

                    Print("Queue transaction aborted");
                }
            }
        }
示例#25
0
 public IActionResult Privacy()
 {
     RabbitMqMessageQueue.Send("MyQueue", "Hello ddd");
     return(View());
 }