using LiveForum.Code.Redis.Contract;
using LiveForum.IService.Others;
using Microsoft.Extensions.Logging;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LiveForum.Service.Others
{
///
/// 缓存清除服务实现
///
public class CacheClearService : ICacheClearService
{
private readonly IRedisService _redisService;
private readonly ILogger _logger;
private const string CACHE_KEY_PREFIX = "cache:api:";
public CacheClearService(
IRedisService redisService,
ILogger logger)
{
_redisService = redisService;
_logger = logger;
}
public async Task ClearAllCacheAsync(string pattern = null)
{
try
{
var searchPattern = pattern ?? $"{CACHE_KEY_PREFIX}*";
var keys = await GetCacheKeysAsync(searchPattern);
if (keys == null || !keys.Any())
{
_logger.LogInformation("[CacheClear] 未找到匹配的缓存Key。Pattern: {Pattern}", searchPattern);
return true;
}
var db = await _redisService.GetDatabaseAsync();
var removedCount = 0;
foreach (var key in keys)
{
await _redisService.RemoveAsync(key);
removedCount++;
}
_logger.LogInformation("[CacheClear] 成功清除 {Count} 个缓存Key。Pattern: {Pattern}", removedCount, searchPattern);
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "[CacheClear] 清除所有缓存失败。Pattern: {Pattern}", pattern);
return false;
}
}
public async Task ClearCacheByControllerAsync(string controller)
{
try
{
if (string.IsNullOrWhiteSpace(controller))
{
_logger.LogWarning("[CacheClear] Controller名称不能为空");
return false;
}
var pattern = $"{CACHE_KEY_PREFIX}{controller}:*";
return await ClearAllCacheAsync(pattern);
}
catch (Exception ex)
{
_logger.LogError(ex, "[CacheClear] 清除指定Controller缓存失败。Controller: {Controller}", controller);
return false;
}
}
public async Task ClearCacheByActionAsync(string controller, string action)
{
try
{
if (string.IsNullOrWhiteSpace(controller) || string.IsNullOrWhiteSpace(action))
{
_logger.LogWarning("[CacheClear] Controller或Action名称不能为空");
return false;
}
var pattern = $"{CACHE_KEY_PREFIX}{controller}:{action}*";
return await ClearAllCacheAsync(pattern);
}
catch (Exception ex)
{
_logger.LogError(ex, "[CacheClear] 清除指定Action缓存失败。Controller: {Controller}, Action: {Action}", controller, action);
return false;
}
}
public async Task ClearCacheByKeyAsync(string cacheKey)
{
try
{
if (string.IsNullOrWhiteSpace(cacheKey))
{
_logger.LogWarning("[CacheClear] 缓存Key不能为空");
return false;
}
await _redisService.RemoveAsync(cacheKey);
_logger.LogInformation("[CacheClear] 成功清除缓存Key: {CacheKey}", cacheKey);
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "[CacheClear] 清除指定Key缓存失败。CacheKey: {CacheKey}", cacheKey);
return false;
}
}
public async Task> GetCacheKeysAsync(string pattern)
{
try
{
var searchPattern = string.IsNullOrWhiteSpace(pattern) ? $"{CACHE_KEY_PREFIX}*" : pattern;
var db = await _redisService.GetDatabaseAsync();
var endpoints = db.Multiplexer.GetEndPoints();
if (endpoints == null || !endpoints.Any())
{
_logger.LogWarning("[CacheClear] 未找到Redis服务器端点");
return new List();
}
var server = db.Multiplexer.GetServer(endpoints.First());
var keys = server.Keys(pattern: searchPattern);
var keyList = keys.Select(k => k.ToString()).ToList();
_logger.LogInformation("[CacheClear] 找到 {Count} 个匹配的缓存Key。Pattern: {Pattern}", keyList.Count, searchPattern);
return keyList;
}
catch (Exception ex)
{
_logger.LogError(ex, "[CacheClear] 获取缓存Key列表失败。Pattern: {Pattern}", pattern);
return new List();
}
}
}
}