You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
2.1 KiB

3 months ago
using System;
using System.Threading;
using System.Threading.Tasks;
using CellularManagement.Domain.Services;
3 months ago
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace CellularManagement.Infrastructure.Services;
/// <summary>
/// 密钥轮换后台服务
/// </summary>
public sealed class KeyRotationBackgroundService : BackgroundService
{
private readonly IKeyRotationService _keyRotationService;
private readonly ILogger<KeyRotationBackgroundService> _logger;
private readonly TimeSpan _checkInterval;
/// <summary>
/// 构造函数
/// </summary>
public KeyRotationBackgroundService(
IKeyRotationService keyRotationService,
ILogger<KeyRotationBackgroundService> logger)
{
_keyRotationService = keyRotationService;
_logger = logger;
_checkInterval = TimeSpan.FromHours(1); // 每小时检查一次
}
/// <inheritdoc />
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
{
// 初始化密钥轮换服务
await _keyRotationService.InitializeAsync();
while (!stoppingToken.IsCancellationRequested)
{
try
{
// 检查是否需要轮换密钥
if (_keyRotationService.ShouldRotateKey())
{
_logger.LogInformation("开始轮换密钥");
await _keyRotationService.RotateKeyAsync();
_logger.LogInformation("密钥轮换完成");
}
}
catch (Exception ex)
{
_logger.LogError(ex, "密钥轮换检查失败: {Message}", ex.Message);
}
// 等待下一次检查
await Task.Delay(_checkInterval, stoppingToken);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "密钥轮换后台服务失败: {Message}", ex.Message);
throw;
}
}
}