Files
vigilcare-clinical/VigilCareClinicalAPI/BackgroundServices/ThresholdCacheLoader.cs
T

48 lines
1.5 KiB
C#

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<ThresholdCacheLoader> _logger;
public ThresholdCacheLoader(
IServiceProvider services,
IConnectionMultiplexer redis,
ILogger<ThresholdCacheLoader> logger)
{
_services = services;
_redis = redis;
_logger = logger;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
using var scope = _services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
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;
}