31 lines
		
	
	
		
			1.1 KiB
		
	
	
	
		
			C#
		
	
	
	
	
	
			
		
		
	
	
			31 lines
		
	
	
		
			1.1 KiB
		
	
	
	
		
			C#
		
	
	
	
	
	
| using Microsoft.Extensions.Diagnostics.HealthChecks;
 | |
| using StackExchange.Redis;
 | |
| 
 | |
| public sealed class RedisConnectionHealthCheck : IHealthCheck
 | |
| {
 | |
|     private readonly string _connectionString;
 | |
|     public RedisConnectionHealthCheck(string connectionString) => _connectionString = connectionString;
 | |
| 
 | |
|     public async Task<HealthCheckResult> CheckHealthAsync(
 | |
|         HealthCheckContext context,
 | |
|         CancellationToken cancellationToken = default)
 | |
|     {
 | |
|         try
 | |
|         {
 | |
|             var options = ConfigurationOptions.Parse(_connectionString);
 | |
|             options.AbortOnConnectFail = false;
 | |
|             options.ConnectTimeout = 2000;   // optional, be snappy
 | |
| 
 | |
|             using var mux = await ConnectionMultiplexer.ConnectAsync(options);
 | |
|             if (!mux.IsConnected) return HealthCheckResult.Unhealthy("Redis not connected.");
 | |
| 
 | |
|             var ping = await mux.GetDatabase().PingAsync();
 | |
|             return HealthCheckResult.Healthy($"Redis OK (ping {ping.TotalMilliseconds:N0} ms)");
 | |
|         }
 | |
|         catch (Exception ex)
 | |
|         {
 | |
|             return HealthCheckResult.Unhealthy("Redis check failed.", ex);
 | |
|         }
 | |
|     }
 | |
| }
 |