Exemple #1
0
        public async Task DispatchAsync_Should_Sent_To_FirstNamespacePart_By_Convention()
        {
            try
            {
                var networkInfos = RabbitNetworkInfos.GetConfigurationFor("CQELight", RabbitMQExchangeStrategy.Custom);
                networkInfos.ServiceQueueDescriptions.Add(new RabbitQueueDescription("CQELight"));
                var config = new RabbitPublisherConfiguration
                {
                    ConnectionInfos = GetConnectionInfos(),
                    NetworkInfos    = networkInfos
                };
                var publisher = new RabbitPublisher(
                    loggerFactory,
                    config);

                await publisher.DispatchAsync(new TestCommand());

                var result = channel.BasicGet("CQELight", true);
                result.Should().NotBeNull();
                Encoding.UTF8.GetString(result.Body.ToArray()).FromJson <TestCommand>().Should().NotBeNull();
            }
            finally
            {
                DeleteData();
            }
        }
Exemple #2
0
        /// <summary>
        /// Use RabbitMQ as Pub/Sub system.
        /// </summary>
        /// <param name="bootstrapper">Bootstrapper instance to configure</param>
        /// <returns>Configured bootstrapper instance</returns>
        public static Bootstrapper UseRabbitMQ(
            this Bootstrapper bootstrapper,
            RabbitConnectionInfos connectionInfos,
            RabbitNetworkInfos networkInfos,
            Action <RabbitSubscriberConfiguration> subscriberConfiguration = null,
            Action <RabbitPublisherConfiguration> publisherConfiguration   = null)
        {
            var service = RabbitMQBootstrappService.Instance;

            var subscriberConf = new RabbitSubscriberConfiguration
            {
                ConnectionInfos = connectionInfos,
                NetworkInfos    = networkInfos
            };

            subscriberConfiguration?.Invoke(subscriberConf);

            service.BootstrappAction += (ctx) =>
            {
                var publisherConf = new RabbitPublisherConfiguration()
                {
                    ConnectionInfos = connectionInfos,
                    NetworkInfos    = networkInfos
                };
                publisherConfiguration?.Invoke(publisherConf);

                bootstrapper.AddIoCRegistration(new InstanceTypeRegistration(subscriberConf, typeof(RabbitSubscriberConfiguration)));
                bootstrapper.AddIoCRegistration(new InstanceTypeRegistration(publisherConf, typeof(RabbitPublisherConfiguration)));

                bootstrapper.AddIoCRegistration(new TypeRegistration(typeof(RabbitPublisher), true));
                bootstrapper.AddIoCRegistration(new TypeRegistration(typeof(RabbitSubscriber), true));
                if (publisherConf.RoutingKeyFactory != null)
                {
                    bootstrapper.AddIoCRegistration(new InstanceTypeRegistration(publisherConf.RoutingKeyFactory, typeof(IRoutingKeyFactory)));
                }
            };
            bootstrapper.AddService(service);
            bootstrapper.OnPostBootstrapping += (c) =>
            {
                ILoggerFactory loggerFactory = null;
                IScopeFactory  scopeFactory  = null;
                if (c.Scope != null)
                {
                    loggerFactory = c.Scope.Resolve <ILoggerFactory>();
                    scopeFactory  = c.Scope.Resolve <IScopeFactory>();
                }
                if (loggerFactory == null)
                {
                    loggerFactory = new LoggerFactory();
                    loggerFactory.AddProvider(new DebugLoggerProvider());
                }
                RabbitMQBootstrappService.RabbitSubscriber =
                    new RabbitSubscriber(
                        loggerFactory,
                        subscriberConf,
                        scopeFactory);
                RabbitMQBootstrappService.RabbitSubscriber.Start();
            };
            return(bootstrapper);
        }
Exemple #3
0
        public async Task PublishAsync_Should_Sent_To_Service_Exchange()
        {
            try
            {
                var networkInfos = RabbitNetworkInfos.GetConfigurationFor("CQELight", RabbitMQExchangeStrategy.Custom);
                networkInfos.ServiceExchangeDescriptions.Add(new RabbitExchangeDescription("pub1_exchange"));
                var config = new RabbitPublisherConfiguration
                {
                    ConnectionInfos = GetConnectionInfos(),
                    NetworkInfos    = networkInfos
                };
                RabbitCommonTools.DeclareExchangesAndQueueForPublisher(channel, config);
                channel.QueueDeclare("CQELight");
                channel.QueueBind("CQELight", "pub1_exchange", "");

                var publisher = new RabbitPublisher(
                    loggerFactory,
                    config);

                await publisher.PublishEventAsync(new TestEvent());

                var result = channel.BasicGet("CQELight", true);
                result.Should().NotBeNull();
                Encoding.UTF8.GetString(result.Body.ToArray()).FromJson <TestCommand>().Should().NotBeNull();
            }
            finally
            {
                DeleteData();
            }
        }
 /// <summary>
 /// Creates a new instance of <see cref="RabbitSubscriberConfiguration"/>.
 /// </summary>
 /// <param name="connectionInfos">Connection infos to reach Rabbit instance/cluster</param>
 /// <param name="networkInfos">Network topology informations</param>
 public RabbitSubscriberConfiguration(
     RabbitConnectionInfos connectionInfos,
     RabbitNetworkInfos networkInfos)
 {
     ConnectionInfos = connectionInfos ?? throw new ArgumentNullException(nameof(connectionInfos));
     NetworkInfos    = networkInfos ?? throw new ArgumentNullException(nameof(networkInfos));
 }
Exemple #5
0
        static void Main(string[] args)
        {
            Console.WriteLine("Trying to connect to RabbitMQ instance @locahost with guest:guest");

            var loggerFactory = new LoggerFactory();

            var network = RabbitNetworkInfos.GetConfigurationFor("client", RabbitMQExchangeStrategy.SingleExchange);
            //This network will produce a client_queue queue, bound to cqelight_global_exchange
            new Bootstrapper()
                .UseRabbitMQ(
                    ConnectionInfosHelper.GetConnectionInfos("client"),
                    network
                )
                .UseAutofacAsIoC(c => c.Register(_ => loggerFactory).AsImplementedInterfaces().ExternallyOwned())
                .Bootstrapp();
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Successfuly connected to RabbitMQ");
            Console.ResetColor();
            Console.WriteLine("Enter your message and press enter to send to server, or enter 'quit' to exit process");
            var data = Console.ReadLine();
            while (data != "quit")
            {
                CoreDispatcher.PublishEventAsync(new NewMessage { Payload = data });
                data = Console.ReadLine();
            }
        }
 /// <summary>
 /// Creates a new Rabbit publishing configuration.
 /// </summary>
 /// <param name="connectionInfos">Connection infos to reach Rabbit instance/cluster</param>
 /// <param name="networkInfos">Network topology informations</param>
 /// <param name="eventsLifetime">Collection of event lifetime informations.</param>
 public RabbitPublisherConfiguration(
     RabbitConnectionInfos connectionInfos,
     RabbitNetworkInfos networkInfos,
     IEnumerable <EventLifeTimeConfiguration>?eventsLifetime = null)
     : base(eventsLifetime ?? Enumerable.Empty <EventLifeTimeConfiguration>())
 {
     ConnectionInfos = connectionInfos ?? throw new System.ArgumentNullException(nameof(connectionInfos));
     NetworkInfos    = networkInfos ?? throw new System.ArgumentNullException(nameof(networkInfos));
 }
Exemple #7
0
        public async Task OneExchangePerService_NetworkConfiguration_AsExpected_Event()
        {
            try
            {
                bool eventReceived = false;
                var  networkInfos  = RabbitNetworkInfos.GetConfigurationFor("sub1", RabbitMQExchangeStrategy.ExchangePerService);

                networkInfos.DistantExchangeDescriptions.Add(
                    new RabbitExchangeDescription(firstProducerEventExchangeName)
                    );

                var serviceQueue = networkInfos.ServiceQueueDescriptions[0];
                serviceQueue.Bindings.Add(new RabbitQueueBindingDescription(firstProducerEventExchangeName));

                var config = new RabbitSubscriberConfiguration
                {
                    UseDeadLetterQueue = false,
                    ConnectionInfos    = GetConnectionInfos(),
                    NetworkInfos       = networkInfos,
                    DispatchInMemory   = false
                };
                config.EventCustomCallback = (e) => eventReceived = e is RabbitEvent;
                var subscriber = new RabbitSubscriber(
                    _loggerFactory,
                    config,
                    scopeFactory);

                subscriber.Start();

                var enveloppeWithFirstEvent = GetEnveloppeDataForEvent(publisher: "pub1", content: "data");

                _channel.BasicPublish(
                    exchange: firstProducerEventExchangeName,
                    routingKey: "",
                    basicProperties: null,
                    body: enveloppeWithFirstEvent);

                int awaitedTime = 0;
                while (awaitedTime <= 2000)
                {
                    if (eventReceived)
                    {
                        break;
                    }
                    await Task.Delay(10);

                    awaitedTime += 10;
                }

                eventReceived.Should().BeTrue();
            }
            finally
            {
                DeleteData();
            }
        }
Exemple #8
0
        public async Task RabbitMQSubscriber_Should_Consider_AckStrategy_Ack_On_Receive_Fail_Should_Remove_MessageFromQueue_CallbackExc()
        {
            try
            {
                var networkInfos = RabbitNetworkInfos.GetConfigurationFor("sub1", RabbitMQExchangeStrategy.SingleExchange);

                var config = new RabbitSubscriberConfiguration
                {
                    UseDeadLetterQueue = true,
                    ConnectionInfos    = GetConnectionInfos(),
                    NetworkInfos       = networkInfos,
                    AckStrategy        = AckStrategy.AckOnReceive
                };
                config.EventCustomCallback += (_) => throw new InvalidOperationException();

                var subscriber = new RabbitSubscriber(
                    _loggerFactory,
                    config);

                subscriber.Start();

                var evt = new ExceptionEvent();

                _channel.BasicPublish(
                    Consts.CONST_CQE_EXCHANGE_NAME,
                    "",
                    body: Encoding.UTF8.GetBytes(
                        JsonConvert.SerializeObject(
                            new Enveloppe(
                                JsonConvert.SerializeObject(evt), typeof(ExceptionEvent), publisher1Name))));
                await Task.Delay(250);

                int            awaitedTime = 0;
                BasicGetResult result      = null;
                while (awaitedTime <= 750)
                {
                    result = _channel.BasicGet(Consts.CONST_DEAD_LETTER_QUEUE_NAME, true);
                    if (result != null)
                    {
                        break;
                    }
                    await Task.Delay(10);

                    awaitedTime += 10;
                }
                result.Should().BeNull();
            }
            finally
            {
                DeleteData();
            }
        }
Exemple #9
0
        public async Task RabbitSubscriber_Should_Consider_AckStrategy_Ack_On_Success_CallbackExc()
        {
            try
            {
                bool eventReceived = false;
                var  messages      = new List <object>();
                var  networkInfos  = RabbitNetworkInfos.GetConfigurationFor("sub1", RabbitMQExchangeStrategy.SingleExchange);

                var config = new RabbitSubscriberConfiguration
                {
                    UseDeadLetterQueue = true,
                    ConnectionInfos    = GetConnectionInfos(),
                    NetworkInfos       = networkInfos,
                    DispatchInMemory   = false
                };
                config.EventCustomCallback = (e) => { messages.Add(e); eventReceived = true; };

                var subscriber = new RabbitSubscriber(
                    _loggerFactory,
                    config);

                subscriber.Start();

                var evt = new AutoAckEvent();

                _channel.BasicPublish(
                    Consts.CONST_CQE_EXCHANGE_NAME,
                    "",
                    body: Encoding.UTF8.GetBytes(
                        JsonConvert.SerializeObject(
                            new Enveloppe(
                                JsonConvert.SerializeObject(evt), typeof(AutoAckEvent), publisher1Name))));
                int awaitedTime = 0;
                while (awaitedTime <= 2000)
                {
                    if (eventReceived)
                    {
                        break;
                    }
                    await Task.Delay(10);

                    awaitedTime += 10;
                }
                eventReceived.Should().BeTrue();
                var result = _channel.BasicGet(Consts.CONST_DEAD_LETTER_QUEUE_NAME, true);
                result.Should().BeNull();
            }
            finally
            {
                DeleteData();
            }
        }
Exemple #10
0
        public async Task Command_Should_Be_Send_AsDirect()
        {
            try
            {
                bool commandReceived = false;
                var  networkInfos    = RabbitNetworkInfos.GetConfigurationFor("sub1", RabbitMQExchangeStrategy.SingleExchange);
                var  serviceQueue    = networkInfos.ServiceQueueDescriptions[0];
                var  config          = new RabbitSubscriberConfiguration
                {
                    UseDeadLetterQueue = false,
                    ConnectionInfos    = GetConnectionInfos(),
                    NetworkInfos       = networkInfos,
                    DispatchInMemory   = false
                };
                config.CommandCustomCallback = (c) => commandReceived = c is RabbitCommand;

                var subscriber = new RabbitSubscriber(
                    _loggerFactory,
                    config,
                    scopeFactory);

                subscriber.Start();

                var enveloppeWithCommand = GetEnveloppeDataForCommand(publisher: "pub1", content: "data");

                _channel.BasicPublish(
                    exchange: "",
                    routingKey: serviceQueue.QueueName,
                    basicProperties: null,
                    body: enveloppeWithCommand);

                int awaitedTime = 0;
                while (awaitedTime <= 2000)
                {
                    if (commandReceived)
                    {
                        break;
                    }
                    await Task.Delay(10);

                    awaitedTime += 10;
                }

                commandReceived.Should().BeTrue();
            }
            finally
            {
                DeleteData();
            }
        }
Exemple #11
0
        public async Task PublishAsync_RoutingKey_Topic_Should_BeConsidered()
        {
            try
            {
                var fakeRoutingKeyFactory = new Mock <IRoutingKeyFactory>();
                fakeRoutingKeyFactory
                .Setup(m => m.GetRoutingKeyForEvent(It.IsAny <object>()))
                .Returns("cqelight.events.testevent");

                var networkInfos = RabbitNetworkInfos.GetConfigurationFor("CQELight", RabbitMQExchangeStrategy.Custom);
                networkInfos.ServiceQueueDescriptions.Add(new RabbitQueueDescription("CQELight"));
                networkInfos.ServiceExchangeDescriptions.Add(new RabbitExchangeDescription("MyCustomExchange")
                {
                    ExchangeType = ExchangeType.Topic
                });
                var queue = new RabbitQueueDescription("MyCustomQueue");
                queue.Bindings.Add(new RabbitQueueBindingDescription("MyCustomExchange")
                {
                    RoutingKeys = new List <string> {
                        "*.events.*"
                    }
                });
                networkInfos.ServiceQueueDescriptions.Add(queue);
                var config = new RabbitPublisherConfiguration
                {
                    ConnectionInfos   = GetConnectionInfos(),
                    NetworkInfos      = networkInfos,
                    RoutingKeyFactory = fakeRoutingKeyFactory.Object
                };
                var publisher = new RabbitPublisher(
                    loggerFactory,
                    config);

                await publisher.PublishEventAsync(new TestEvent());

                channel.BasicGet("CQELight", true).Should().BeNull();

                var result = channel.BasicGet("MyCustomQueue", true);
                result.Should().NotBeNull();
                Encoding.UTF8.GetString(result.Body.ToArray()).FromJson <TestEvent>().Should().NotBeNull();
            }
            finally
            {
                DeleteData();
                channel.QueueDelete("MyCustomQueue");
                channel.ExchangeDelete("MyCustomExchange");
            }
        }
Exemple #12
0
        public async Task OneExchange_Network_Configuration_AsExpected_Event()
        {
            try
            {
                bool eventReceived = false;
                var  networkInfos  = RabbitNetworkInfos.GetConfigurationFor("sub1", RabbitMQExchangeStrategy.SingleExchange);
                var  config        = new RabbitSubscriberConfiguration
                {
                    UseDeadLetterQueue = false,
                    ConnectionInfos    = GetConnectionInfos(),
                    NetworkInfos       = networkInfos,
                    DispatchInMemory   = false
                };
                config.EventCustomCallback = (e) => eventReceived = e is RabbitEvent;
                var subscriber = new RabbitSubscriber(
                    _loggerFactory,
                    config,
                    scopeFactory);

                subscriber.Start();

                var enveloppeWithFirstEvent = GetEnveloppeDataForEvent(publisher: "pub1", content: "data");

                _channel.BasicPublish(
                    exchange: Consts.CONST_CQE_EXCHANGE_NAME,
                    routingKey: "",
                    basicProperties: null,
                    body: enveloppeWithFirstEvent);

                int awaitedTime = 0;
                while (awaitedTime <= 2000)
                {
                    if (eventReceived)
                    {
                        break;
                    }
                    await Task.Delay(10);

                    awaitedTime += 10;
                }

                eventReceived.Should().BeTrue();
            }
            finally
            {
                DeleteData();
            }
        }
Exemple #13
0
        public async Task DispatchAsync_Default_Routing_Key_Factory_Should_Be_Considered()
        {
            try
            {
                var fakeRoutingKeyFactory = new Mock <IRoutingKeyFactory>();
                fakeRoutingKeyFactory
                .Setup(m => m.GetRoutingKeyForCommand(It.IsAny <object>()))
                .Returns("MyCustomQueue");

                var networkInfos = RabbitNetworkInfos.GetConfigurationFor("CQELight", RabbitMQExchangeStrategy.Custom);
                networkInfos.ServiceQueueDescriptions.Add(new RabbitQueueDescription("CQELight"));
                networkInfos.ServiceQueueDescriptions.Add(new RabbitQueueDescription("MyCustomQueue"));
                var config = new RabbitPublisherConfiguration
                {
                    ConnectionInfos   = GetConnectionInfos(),
                    NetworkInfos      = networkInfos,
                    RoutingKeyFactory = fakeRoutingKeyFactory.Object
                };
                var publisher = new RabbitPublisher(
                    loggerFactory,
                    config);

                await publisher.DispatchAsync(new TestCommand());

                channel.BasicGet("CQELight", true).Should().BeNull();

                var result = channel.BasicGet("MyCustomQueue", true);
                result.Should().NotBeNull();
                Encoding.UTF8.GetString(result.Body.ToArray()).FromJson <TestCommand>().Should().NotBeNull();
            }
            finally
            {
                DeleteData();
                channel.QueueDelete("MyCustomQueue");
            }
        }
Exemple #14
0
        static void Main(string[] args)
        {
            Console.WriteLine("Trying to connect to RabbitMQ instance @locahost with guest:guest");

            var loggerFactory = new LoggerFactory();

            var network = RabbitNetworkInfos.GetConfigurationFor("server", RabbitMQExchangeStrategy.SingleExchange);

            //This network will produce a client_queue queue, bound to cqelight_global_exchange
            new Bootstrapper()
            .UseRabbitMQ(
                ConnectionInfosHelper.GetConnectionInfos("server"),
                network,
                cfg => cfg.DispatchInMemory = true
                )
            .UseInMemoryEventBus()
            .UseAutofacAsIoC(c => c.Register(_ => loggerFactory).AsImplementedInterfaces().ExternallyOwned())
            .Bootstrapp();
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Successfuly connected to RabbitMQ");
            Console.ResetColor();
            Console.WriteLine("Listening... Press any key to exit");
            Console.ReadLine();
        }