83 lines
3.2 KiB
C#
83 lines
3.2 KiB
C#
using iFileProxy.Config;
|
|
using iFileProxy.Helpers;
|
|
using iFileProxy.Models;
|
|
using Newtonsoft.Json;
|
|
using Serilog;
|
|
|
|
namespace iFileProxy.Services
|
|
{
|
|
/// <summary>
|
|
/// 本地缓存管理器
|
|
/// </summary>
|
|
public class LocalCacheManager
|
|
{
|
|
// 禁用空警告 因为初始化的时候就已经检查过相关的内容了
|
|
#pragma warning disable CS8601
|
|
private readonly AppConfig _appConfig = AppConfig.GetCurrConfig();
|
|
private readonly static Serilog.ILogger _logger = Log.Logger.ForContext<LocalCacheManager>();
|
|
|
|
private readonly Timer _timer;
|
|
private readonly DatabaseGateService _dbGateService;
|
|
private readonly int CACHE_LIFETIME;
|
|
|
|
/// <summary>
|
|
/// 缓存管理器
|
|
/// </summary>
|
|
public LocalCacheManager(IServiceProvider serviceProvider)
|
|
{
|
|
_logger.Information("Initializing LocalCacheManager.");
|
|
CACHE_LIFETIME = _appConfig.DownloadOptions.CacheLifetime;
|
|
_dbGateService = serviceProvider.GetRequiredService<DatabaseGateService>();
|
|
// 开始定时清理任务
|
|
_timer = new Timer(CheckAndCleanCache, null, TimeSpan.FromSeconds(6), TimeSpan.FromSeconds(60));
|
|
_logger.Information("succ.");
|
|
}
|
|
|
|
/// <summary>
|
|
/// 检查并且清理缓存数据
|
|
/// </summary>
|
|
public void CheckAndCleanCache(object state)
|
|
{
|
|
// 初始化并打开一个MySQL连接 防止后续数据过多导致程序crush
|
|
using var dbConn = _dbGateService.GetAndOpenDBConn(DbConfigName.iFileProxy);
|
|
|
|
// 获取数据库中超出生命周期的缓存数据
|
|
string result = _dbGateService.QueryTableData($"SELECT * FROM t_tasks_info WHERE UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(update_time) > {CACHE_LIFETIME} AND (tag <> 'CLEANED' OR tag IS NULL)", DbConfigName.iFileProxy);
|
|
List<TaskInfo>? taskInfos = JsonConvert.DeserializeObject<List<TaskInfo>>(result);
|
|
if (taskInfos != null)
|
|
{
|
|
foreach (TaskInfo taskInfo in taskInfos)
|
|
{
|
|
string cacheFileName = Path.Combine(_appConfig.DownloadOptions.SavePath, taskInfo.FileName);
|
|
if (File.Exists(cacheFileName))
|
|
{
|
|
_logger.Information($"正在清理缓存文件: {cacheFileName}");
|
|
try
|
|
{
|
|
File.Delete(cacheFileName);
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
_logger.Error("缓存文件删除失败: {e}", e);
|
|
throw;
|
|
}
|
|
}
|
|
_dbGateService.Query($"UPDATE t_tasks_info SET `tag` = \"CLEANED\" WHERE `tid` = '{taskInfo.TaskId}'", dbConn);
|
|
taskInfo.Status = TaskState.Cleaned;
|
|
_dbGateService.UpdateTaskStatus(taskInfo,dbConn);
|
|
}
|
|
}
|
|
|
|
|
|
}
|
|
|
|
/// <summary>
|
|
/// 停止定时清理服务
|
|
/// </summary>
|
|
public void StopScheduledCleanupService()
|
|
{
|
|
_timer.Dispose();
|
|
}
|
|
|
|
}
|
|
}
|