Esempio n. 1
0
        static void ExecuteSuccessfulConnectionCreationAndAssertResults(RabbitMqClientOptions connectionOptions)
        {
            var connectionFactory = new RabbitMqConnectionFactory();

            using var connection = connectionFactory.CreateRabbitMqConnection(connectionOptions);
            Assert.True(connection.IsOpen);
        }
Esempio n. 2
0
        static void ConfigureServices(IServiceCollection services)
        {
            var rabbitMqConfiguration = new RabbitMqClientOptions
            {
                HostName    = "gull-01.rmq.cloudamqp.com",
                Port        = 5672,
                UserName    = "******",
                Password    = "******",
                VirtualHost = "noekmbda"
            };
            var exchangeOptions = new RabbitMqExchangeOptions
            {
                Type    = "topic",
                Durable = false,
                Queues  = new List <RabbitMqQueueOptions>
                {
                    new RabbitMqQueueOptions
                    {
                        Name        = "testqueue",
                        Durable     = false,
                        RoutingKeys = new HashSet <string> {
                            "routing.key"
                        }
                    }
                }
            };

            services.AddRabbitMqClient(rabbitMqConfiguration)
            .AddProductionExchange("message", exchangeOptions);
        }
        /// <summary>
        /// Create a RabbitMQ connection.
        /// </summary>
        /// <param name="options">An instance of options <see cref="RabbitMqClientOptions"/>.</param>
        /// <returns>An instance of connection <see cref="IConnection"/>.</returns>
        /// <remarks>If options parameter is null the method return null too.</remarks>
        internal static IConnection CreateRabbitMqConnection(RabbitMqClientOptions options)
        {
            if (options is null)
            {
                return(null);
            }

            var factory = new ConnectionFactory
            {
                Port        = options.Port,
                UserName    = options.UserName,
                Password    = options.Password,
                VirtualHost = options.VirtualHost,
                AutomaticRecoveryEnabled   = options.AutomaticRecoveryEnabled,
                TopologyRecoveryEnabled    = options.TopologyRecoveryEnabled,
                RequestedConnectionTimeout = options.RequestedConnectionTimeout,
                RequestedHeartbeat         = options.RequestedHeartbeat,
                DispatchConsumersAsync     = true
            };

            if (options.TcpEndpoints?.Any() == true)
            {
                var clientEndpoints = options.TcpEndpoints.Select(x => new AmqpTcpEndpoint(x.HostName, x.Port)).ToList();
                return(factory.CreateConnection(clientEndpoints));
            }

            return(string.IsNullOrEmpty(options.ClientProvidedName)
                ? CreateConnection(options, factory)
                : CreateNamedConnection(options, factory));
        }
        public static async Task Main()
        {
            var builder = new HostBuilder()
                          .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.AddJsonFile("appsettings.json", optional: false);
            })
                          .ConfigureServices((hostContext, services) =>
            {
                // Let's configure two different BatchMessageHandlers with different methods.
                // First - configuring an appsettings.json section.
                services.AddBatchMessageHandler <CustomBatchMessageHandler>(hostContext.Configuration.GetSection("RabbitMq"));

                // Second one - passing configuration instance.
                var rabbitMqConfiguration = new RabbitMqClientOptions
                {
                    HostName = "127.0.0.1",
                    Port     = 5672,
                    UserName = "******",
                    Password = "******"
                };
                services.AddBatchMessageHandler <CustomBatchMessageHandler>(rabbitMqConfiguration);

                // Use either of them. Do not register batch message handlers multiple times in your real project.
            })
                          .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddConsole();
            });
            await builder.RunConsoleAsync();
        }
Esempio n. 5
0
        static void ConfigureServices(IServiceCollection services)
        {
            var rabbitMqConfiguration = new RabbitMqClientOptions
            {
                HostName = "127.0.0.1",
                Port     = 5672,
                UserName = "******",
                Password = "******"
            };
            var exchangeOptions = new RabbitMqExchangeOptions
            {
                Queues = new List <RabbitMqQueueOptions>
                {
                    new RabbitMqQueueOptions
                    {
                        Name        = "myqueue",
                        RoutingKeys = new HashSet <string> {
                            "routing.key"
                        }
                    }
                }
            };

            services.AddRabbitMqClient(rabbitMqConfiguration)
            .AddProductionExchange("exchange.name", exchangeOptions);
        }
Esempio n. 6
0
        internal static RabbitMqClientOptions GetRabbitMqClientOptionsInstance(IConfiguration configuration)
        {
            var options = new RabbitMqClientOptions();

            configuration.Bind(options);
            return(options);
        }
        /// <summary>
        /// Create a RabbitMQ connection.
        /// </summary>
        /// <param name="options">An instance of options <see cref="RabbitMqClientOptions"/>.</param>
        /// <returns>An instance of connection <see cref="IConnection"/>.</returns>
        /// <remarks>If options parameter is null the method return null too.</remarks>
        public IConnection CreateRabbitMqConnection(RabbitMqClientOptions options)
        {
            if (options is null)
            {
                return(null);
            }

            var factory = new ConnectionFactory
            {
                Port        = options.Port,
                UserName    = options.UserName,
                Password    = options.Password,
                VirtualHost = options.VirtualHost,
                AutomaticRecoveryEnabled   = options.AutomaticRecoveryEnabled,
                TopologyRecoveryEnabled    = options.TopologyRecoveryEnabled,
                RequestedConnectionTimeout = options.RequestedConnectionTimeout,
                RequestedHeartbeat         = options.RequestedHeartbeat,
                DispatchConsumersAsync     = true
            };

            if (options.TcpEndpoints?.Any() == true)
            {
                return(CreateConnectionWithTcpEndpoints(options, factory));
            }

            return(string.IsNullOrEmpty(options.ClientProvidedName)
                ? CreateConnection(options, factory)
                : CreateNamedConnection(options, factory));
        }
        static IConnection CreateConnectionWithTcpEndpoints(RabbitMqClientOptions options, ConnectionFactory factory)
        {
            var clientEndpoints = new List <AmqpTcpEndpoint>();

            foreach (var endpoint in options.TcpEndpoints)
            {
                var sslOption = endpoint.SslOption;
                if (sslOption != null)
                {
                    var convertedOption = new SslOption(sslOption.ServerName, sslOption.CertificatePath, sslOption.Enabled);
                    if (!string.IsNullOrEmpty(sslOption.CertificatePassphrase))
                    {
                        convertedOption.CertPassphrase = sslOption.CertificatePassphrase;
                    }

                    if (sslOption.AcceptablePolicyErrors != null)
                    {
                        convertedOption.AcceptablePolicyErrors = sslOption.AcceptablePolicyErrors.Value;
                    }

                    clientEndpoints.Add(new AmqpTcpEndpoint(endpoint.HostName, endpoint.Port, convertedOption));
                }
                else
                {
                    clientEndpoints.Add(new AmqpTcpEndpoint(endpoint.HostName, endpoint.Port));
                }
            }
            return(TryToCreateConnection(() => factory.CreateConnection(clientEndpoints), options.InitialConnectionRetries, options.InitialConnectionRetryTimeoutMilliseconds));
        }
Esempio n. 9
0
        static void ExecuteUnsuccessfulConnectionCreationAndAssertResults(RabbitMqClientOptions connectionOptions)
        {
            var connectionFactory = new RabbitMqConnectionFactory();
            var exception         = Assert.Throws <InitialConnectionException>(() => connectionFactory.CreateRabbitMqConnection(connectionOptions));

            Assert.Equal(connectionOptions.InitialConnectionRetries, exception.NumberOfRetries);
        }
 public LimitedHandlerRunner(
     IConsumerErrorStrategy consumerErrorStrategy,
     RabbitMqClientOptions rabbitMqClientOptions)
     : base(consumerErrorStrategy)
 {
     _rabbitMqClientOptions = rabbitMqClientOptions;
 }
        static IConnection CreateConnection(RabbitMqClientOptions options, ConnectionFactory factory)
        {
            if (options.HostNames?.Any() == true)
            {
                return(factory.CreateConnection(options.HostNames.ToList()));
            }

            factory.HostName = options.HostName;
            return(factory.CreateConnection());
        }
Esempio n. 12
0
 public RabbitMqConsumerBackgroundWorker(ILogger <RabbitMqConsumerBackgroundWorker> logger,
                                         IServiceProvider serviceProvider,
                                         IServiceScopeFactory serviceScopeFactory,
                                         IOptions <RabbitMqClientOptions> rabbitMqClientOptionsAccessor)
 {
     _logger              = logger;
     _serviceProvider     = serviceProvider;
     _serviceScopeFactory = serviceScopeFactory;
     _options             = rabbitMqClientOptionsAccessor.Value;
 }
        static IConnection CreateNamedConnection(RabbitMqClientOptions options, ConnectionFactory factory)
        {
            if (options.HostNames?.Any() == true)
            {
                return(TryToCreateConnection(() => factory.CreateConnection(options.HostNames.ToList(), options.ClientProvidedName), options.InitialConnectionRetries, options.InitialConnectionRetryTimeoutMilliseconds));
            }

            factory.HostName = options.HostName;
            return(TryToCreateConnection(() => factory.CreateConnection(options.ClientProvidedName), options.InitialConnectionRetries, options.InitialConnectionRetryTimeoutMilliseconds));
        }
Esempio n. 14
0
        public void ShouldProperlyCreateInitialConnection()
        {
            var connectionOptions = new RabbitMqClientOptions
            {
                HostName = "rabbitmq",
                InitialConnectionRetries = 1,
                InitialConnectionRetryTimeoutMilliseconds = 20
            };

            ExecuteSuccessfulConnectionCreationAndAssertResults(connectionOptions);
        }
Esempio n. 15
0
        public void ShouldProperlyRetryCreatingInitialConnection(int retries)
        {
            var connectionOptions = new RabbitMqClientOptions
            {
                HostName = "anotherHost",
                InitialConnectionRetries = retries,
                InitialConnectionRetryTimeoutMilliseconds = 20
            };

            ExecuteUnsuccessfulConnectionCreationAndAssertResults(connectionOptions);
        }
Esempio n. 16
0
        public void ShouldProperlyCreateInitialConnectionWithHostNamesAndNamedConnection()
        {
            var connectionOptions = new RabbitMqClientOptions
            {
                HostNames = new List <string> {
                    "rabbitmq"
                },
                ClientProvidedName       = "connectionName",
                InitialConnectionRetries = 3,
                InitialConnectionRetryTimeoutMilliseconds = 20
            };

            ExecuteSuccessfulConnectionCreationAndAssertResults(connectionOptions);
        }
        protected BaseBatchMessageHandler(
            IRabbitMqConnectionFactory rabbitMqConnectionFactory,
            IEnumerable <BatchConsumerConnectionOptions> batchConsumerConnectionOptions,
            ILogger <BaseBatchMessageHandler> logger)
        {
            var optionsContainer = batchConsumerConnectionOptions.FirstOrDefault(x => x.Type == GetType());

            if (optionsContainer is null)
            {
                throw new ArgumentNullException($"Client connection options for {nameof(BaseBatchMessageHandler)} has not been found.", nameof(batchConsumerConnectionOptions));
            }

            _clientOptions             = optionsContainer.ClientOptions ?? throw new ArgumentNullException($"Consumer client options is null for {nameof(BaseBatchMessageHandler)}.", nameof(optionsContainer.ClientOptions));
            _rabbitMqConnectionFactory = rabbitMqConnectionFactory;
            _logger = logger;
        }
Esempio n. 18
0
        public void ShouldProperlyCreateInitialConnectionWithTcpEndpoints()
        {
            var connectionOptions = new RabbitMqClientOptions
            {
                TcpEndpoints = new List <RabbitMqTcpEndpoint>
                {
                    new RabbitMqTcpEndpoint
                    {
                        HostName = "rabbitmq"
                    }
                },
                InitialConnectionRetries = 3,
                InitialConnectionRetryTimeoutMilliseconds = 20
            };

            ExecuteSuccessfulConnectionCreationAndAssertResults(connectionOptions);
        }
Esempio n. 19
0
        public RabbitMqMessageProducer(IServiceProvider serviceProvider,
                                       ILogger <RabbitMqMessageProducer> logger,
                                       IOptions <RabbitMqClientOptions> rabbitMqClientOptionsAccessor)
        {
            _serviceProvider = serviceProvider;
            _logger          = logger;

            _options = rabbitMqClientOptionsAccessor.Value;

            _defaultRetryPolicyAsync = Policy
                                       .Handle <Exception>()
                                       .WaitAndRetryAsync(
                retryCount: (int)_defaultPublishRetryCount,
                sleepDurationProvider: retryAttempt => TimeSpan.FromMilliseconds(_defaultPublishRetryInterval));

            _defaultRetryPolicy = Policy
                                  .Handle <Exception>()
                                  .WaitAndRetry(
                retryCount: (int)_defaultPublishRetryCount,
                sleepDurationProvider: retryAttempt => TimeSpan.FromMilliseconds(_defaultPublishRetryInterval));
        }
Esempio n. 20
0
 /// <summary>
 /// Add RabbitMQ client and required service infrastructure.
 /// </summary>
 /// <param name="services">Service collection.</param>
 /// <param name="configuration">RabbitMq configuration <see cref="RabbitMqClientOptions"/>.</param>
 /// <returns>Service collection.</returns>
 public static IServiceCollection AddRabbitMqClient(this IServiceCollection services, RabbitMqClientOptions configuration)
 {
     services.AddLogging(options => options.AddConsole());
     services.Configure <RabbitMqClientOptions>(opt =>
     {
         opt.HostName    = configuration.HostName;
         opt.Port        = configuration.Port;
         opt.UserName    = configuration.UserName;
         opt.Password    = configuration.Password;
         opt.VirtualHost = configuration.VirtualHost;
         opt.AutomaticRecoveryEnabled   = configuration.AutomaticRecoveryEnabled;
         opt.TopologyRecoveryEnabled    = configuration.TopologyRecoveryEnabled;
         opt.RequestedConnectionTimeout = configuration.RequestedConnectionTimeout;
         opt.RequestedHeartbeat         = configuration.RequestedHeartbeat;
     });
     services.AddSingleton <IQueueService, QueueService>();
     return(services);
 }
        /// <summary>
        /// Add a singleton producing RabbitMQ client and required service infrastructure.
        /// </summary>
        /// <param name="services">Service collection.</param>
        /// <param name="configuration">RabbitMq configuration <see cref="RabbitMqClientOptions"/>.</param>
        /// <returns>Service collection.</returns>
        public static IServiceCollection AddRabbitMqProducingClientSingleton(this IServiceCollection services, RabbitMqClientOptions configuration)
        {
            services.CheckIfQueueingServiceAlreadyConfigured <IProducingService>();
            services.AddRabbitMqClientInfrastructure();
            var guid = Guid.NewGuid();

            services.ConfigureRabbitMqProducingClientOptions(guid, configuration);
            services.ResolveSingletonProducingService(guid);
            return(services);
        }
        /// <summary>
        /// Add a transient fully-functional RabbitMQ client and required service infrastructure.
        /// </summary>
        /// <remarks>
        /// QueueService will be added in the transient mode.
        /// </remarks>
        /// <param name="services">Service collection.</param>
        /// <param name="configuration">RabbitMq configuration <see cref="RabbitMqClientOptions"/>.</param>
        /// <returns>Service collection.</returns>
        public static IServiceCollection AddRabbitMqClientTransient(this IServiceCollection services, RabbitMqClientOptions configuration)
        {
            services.CheckIfQueueingServiceAlreadyConfigured <IQueueService>();
            services.AddRabbitMqClientInfrastructure();
            var guid = Guid.NewGuid();

            services.ConfigureRabbitMqConnectionOptions(guid, configuration);
            services.ResolveTransientQueueService(guid);
            return(services);
        }
Esempio n. 23
0
        internal static IServiceCollection ConfigureRabbitMqConnectionOptions(this IServiceCollection services, Guid guid, RabbitMqClientOptions options)
        {
            var container = new RabbitMqConnectionOptionsContainer
            {
                Guid    = guid,
                Options = new RabbitMqConnectionOptions
                {
                    ProducerOptions = options,
                    ConsumerOptions = options
                }
            };

            return(services.AddRabbitMqConnectionOptionsContainer(container));
        }
 /// <summary>
 /// Add batch message handler.
 /// </summary>
 /// <typeparam name="TBatchMessageHandler">Batch message handler type.</typeparam>
 /// <param name="services">Service collection.</param>
 /// <param name="configuration">RabbitMq configuration <see cref="RabbitMqClientOptions"/>.</param>
 /// <returns>Service collection.</returns>
 public static IServiceCollection AddBatchMessageHandler <TBatchMessageHandler>(this IServiceCollection services, RabbitMqClientOptions configuration)
     where TBatchMessageHandler : BaseBatchMessageHandler
 {
     CheckIfBatchMessageHandlerAlreadyConfigured <TBatchMessageHandler>(services);
     services.TryAddSingleton <IRabbitMqConnectionFactory, RabbitMqConnectionFactory>();
     services.ConfigureBatchConsumerConnectionOptions <TBatchMessageHandler>(configuration);
     services.AddHostedService <TBatchMessageHandler>();
     return(services);
 }
        static IServiceCollection ConfigureBatchConsumerConnectionOptions <TBatchMessageHandler>(this IServiceCollection services, RabbitMqClientOptions clientOptions)
            where TBatchMessageHandler : BaseBatchMessageHandler
        {
            var options = new BatchConsumerConnectionOptions
            {
                Type          = typeof(TBatchMessageHandler),
                ClientOptions = clientOptions
            };
            var serviceDescriptor = new ServiceDescriptor(typeof(BatchConsumerConnectionOptions), options);

            services.Add(serviceDescriptor);
            return(services);
        }