Rename the RabbitMQ options type to make its purpose explicit and update all consumers in the RabbitMQ, Infrastructure, Publisher, Client and test projects. Inline the connection factory registration in the DI extensions instead of the private AddDefaultServices helper. BREAKING CHANGE: RabbitMqConfiguration is now RabbitMqConnectionConfiguration.
52 lines
1.9 KiB
C#
52 lines
1.9 KiB
C#
using DigitalData.MessagingService.Application.Common.Interfaces;
|
|
using DigitalData.MessagingService.RabbitMQ;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace DigitalData.MessagingService.Infrastructure.Queue;
|
|
|
|
/// <summary>
|
|
/// Manages a pool of <see cref="SendingEmailConsumer"/> instances that compete for messages
|
|
/// on the same RabbitMQ queue (competing consumers pattern).
|
|
/// </summary>
|
|
public sealed class SendingEmailConsumerPool : IAsyncDisposable
|
|
{
|
|
private readonly List<SendingEmailConsumer> _consumers;
|
|
private readonly ILogger<SendingEmailConsumerPool>? _logger;
|
|
private readonly int _concurrency;
|
|
|
|
public SendingEmailConsumerPool(
|
|
IOptions<RabbitMqConnectionConfiguration> config,
|
|
IEmailService emailService,
|
|
IServiceScopeFactory scopeFactory,
|
|
RabbitMqConnectionFactory cnnFactory,
|
|
ILogger<SendingEmailConsumerPool>? logger = null,
|
|
ILogger<SendingEmailConsumer>? consumerLogger = null)
|
|
{
|
|
_logger = logger;
|
|
_concurrency = config.Value.ConsumerConcurrency;
|
|
|
|
_consumers = [.. Enumerable
|
|
.Range(0, _concurrency)
|
|
.Select(_ => new SendingEmailConsumer(config.Value.QueueName, emailService, scopeFactory, cnnFactory, consumerLogger))];
|
|
}
|
|
|
|
/// <summary>
|
|
/// Starts all consumers in parallel. Each consumer opens its own channel and begins listening.
|
|
/// </summary>
|
|
public async Task InitAsync()
|
|
{
|
|
_logger?.LogInformation("Starting {Count} competing email consumers.", _concurrency);
|
|
|
|
await Task.WhenAll(_consumers.Select(c => c.InitAsync()));
|
|
|
|
_logger?.LogInformation("All {Count} email consumers started.", _concurrency);
|
|
}
|
|
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
await Task.WhenAll(_consumers.Select(async c => await c.DisposeAsync().AsTask()));
|
|
}
|
|
}
|