public async Task PublishAsync(string topic, byte[] bytes) { if (bytes == null) { throw new ArgumentNullException(nameof(bytes)); } if (!_connection.IsConnected) { _connection.TryConnect(); } var policy = Policy.Handle <BrokerUnreachableException>() .Or <SocketException>() .WaitAndRetry(_options.RetryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) => { _logger.LogWarning(ex, "Could not publish data after {Timeout}s ({ExceptionMessage})", $"{time.TotalSeconds:n1}", ex.Message); }); var channel = _connection.CreateModel(); _logger.LogTrace("Declaring RabbitMQ exchange to publish event"); channel.ExchangeDeclare(exchange: _options.Exchange, type: "direct"); policy.Execute(() => { var properties = channel.CreateBasicProperties(); properties.DeliveryMode = 2; // persistent _logger.LogTrace("Publishing event to RabbitMQ"); channel.BasicPublish(_options.Exchange, topic, true, properties, bytes); channel.Dispose(); }); await Task.CompletedTask; }
public RabbitMQMessageQueue(IOptions <RabbitMQOptions> options, ILoggerFactory loggerFactory) { _logger = loggerFactory.CreateLogger <RabbitMQMessageQueue>(); _options = options.Value; _connection = new PersistentConnection(CreateConnectionFactory(), loggerFactory.CreateLogger <PersistentConnection>(), _options.RetryCount); if (!_connection.IsConnected) { _connection.TryConnect(); } _logger.LogTrace("Creating RabbitMQ publish channel"); _publishChannel = _connection.CreateModel(); _publishChannel.ExchangeDeclare(exchange: _options.Exchange, type: "direct", durable: true); }
public void CloseQueue(string queue) { using var channel = _connection.CreateModel(); channel.QueueDelete(queue); }