|
|
|
using System;
|
|
|
|
using System.Threading;
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
using CellularManagement.Domain.Services;
|
|
|
|
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;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|