using System.Text.Json; using Microsoft.EntityFrameworkCore; using StackExchange.Redis; public class ThresholdCacheLoader : IHostedService { private readonly IServiceProvider _services; private readonly IConnectionMultiplexer _redis; private readonly ILogger _logger; public ThresholdCacheLoader( IServiceProvider services, IConnectionMultiplexer redis, ILogger logger) { _services = services; _redis = redis; _logger = logger; } public async Task StartAsync(CancellationToken cancellationToken) { using var scope = _services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var cache = _redis.GetDatabase(); var thresholds = await db.AlertThresholds.ToListAsync(cancellationToken); var batch = cache.CreateBatch(); foreach (var t in thresholds) { var json = JsonSerializer.Serialize(new { t.ObservationCode, t.CriticalLow, t.WarningLow, t.WarningHigh, t.CriticalHigh }); _ = batch.StringSetAsync($"threshold:{t.ObservationCode}", json); } batch.Execute(); _logger.LogInformation("Loaded {Count} alert thresholds into Redis cache", thresholds.Count); } public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; }