Skip to content

Instantly share code, notes, and snippets.

@alejofv
Created September 5, 2024 18:31
Show Gist options
  • Select an option

  • Save alejofv/f5cbfd438a57d3f34df01bbb90811768 to your computer and use it in GitHub Desktop.

Select an option

Save alejofv/f5cbfd438a57d3f34df01bbb90811768 to your computer and use it in GitHub Desktop.
// _queueHealthCheck is injected as a singleton
private async Task<IConnection> EnsureRabbitMqConnection()
{
while (true)
{
try
{
var connection = _connectionFactory();
connection.ConnectionBlocked += (_, args) =>
{
_queueHealthCheck.SetAsUnhealthy("RabbitMQ queue blocked");
_logger.LogWarning("RabbitMQ connection blocked: {Reason}", args.Reason);
};
connection.ConnectionUnblocked += (_, _) =>
{
_queueHealthCheck.SetAsHealthy();
_logger.LogInformation("RabbitMQ connection unblocked");
};
_queueHealthCheck.SetAsHealthy();
_logger.LogInformation("RabbitMQ connection established. Heartbeat {RabbitMQHeartbeat}", connection.Heartbeat);
return connection;
}
catch (Exception ex)
{
_logger.LogWarning("Problem connecting to RabbitMQ: {Message}. Retrying", ex.Message);
await Task.Delay(TimeSpan.FromSeconds(5));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment