基于Dictionary和定时清理机制,实现支持自动过期的本地缓存,避免内存溢出。
using System.Collections.Concurrent;
using System.Timers;
public class ExpirableLocalCache
{
// 线程安全字典存储缓存项
private readonly ConcurrentDictionary _cache = new();
// 定时清理器(每分钟检查一次)
private readonly Timer _cleanupTimer;
private readonly object _lockObj = new();
public ExpirableLocalCache()
{
_cleanupTimer = new Timer(60000);
_cleanupTimer.Elapsed += OnCleanupTimerElapsed;
_cleanupTimer.Start();
}
// 缓存项模型
private class CacheItem
{
public object Value { get; set; }
public DateTime ExpireTime { get; set; }
public bool IsExpired => DateTime.Now > ExpireTime;
}
// 添加缓存(设置过期时间)
public void Set(string key, object value, TimeSpan expireAfter)
{
_cache[key] = new CacheItem
{
Value = value,
ExpireTime = DateTime.Now.Add(expireAfter)
};
}
// 获取缓存
public T Get<T>(string key) where T : class
{
if (_cache.TryGetValue(key, out var item) && !item.IsExpired)
{
return item.Value as T;
}
_cache.TryRemove(key, out _);
return null;
}
// 主动移除缓存
public void Remove(string key)
{
_cache.TryRemove(key, out _);
}
// 定时清理过期缓存
private void OnCleanupTimerElapsed(object sender, ElapsedEventArgs e)
{
lock (_lockObj)
{
var expiredKeys = _cache.Where(kv => kv.Value.IsExpired)
.Select(kv => kv.Key)
.ToList();
foreach (var key in expiredKeys)
{
_cache.TryRemove(key, out _);
}
Console.WriteLine($"清理了 {expiredKeys.Count} 个过期缓存项");
}
}
// 调用示例
public static void TestCache()
{
var cache = new ExpirableLocalCache();
// 缓存5分钟
cache.Set("user_1", new { Id = 1, Name = "张三" }, TimeSpan.FromMinutes(5));
var user = cache.Get<dynamic>("user_1");
Console.WriteLine($"获取缓存:{user?.Name}");
}
}