feat: 显示缓存 Clear 方法

This commit is contained in:
Argo-Lenovo 2022-01-10 19:09:42 +08:00
parent b281d05c5d
commit f712b0ab0e
1 changed files with 48 additions and 7 deletions

View File

@ -1,19 +1,27 @@
using BootstrapBlazor.Web.Core;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Primitives;
namespace BootstrapAdmin.Web.Core.Services;
class DefaultCacheManager : ICacheManager
{
private IMemoryCache Cache { get; }
[NotNull]
private IMemoryCache? Cache { get; set; }
private List<string> Keys { get; } = new List<string>(256);
private List<(string Key, CancellationTokenSource Token)> Keys { get; } = new(256);
/// <summary>
///
/// </summary>
public DefaultCacheManager()
private DefaultCacheManager()
{
Init();
}
private void Init()
{
Keys.Clear();
Cache = new MemoryCache(new MemoryCacheOptions());
}
@ -38,21 +46,54 @@ class DefaultCacheManager : ICacheManager
private void HandlerEntry(string key, ICacheEntry entry)
{
Keys.Add(key);
entry.SetAbsoluteExpiration(TimeSpan.FromSeconds(10));
(string Key, CancellationTokenSource Token) cacheKey = new();
cacheKey.Key = key;
if (entry.AbsoluteExpiration == null || entry.SlidingExpiration == null || entry.AbsoluteExpirationRelativeToNow == null)
{
// 缓存 10 分钟
entry.SlidingExpiration = TimeSpan.FromSeconds(600);
}
if (entry.ExpirationTokens.Count == 0)
{
// 增加缓存 Token
cacheKey.Token = new CancellationTokenSource();
entry.AddExpirationToken(new CancellationChangeToken(cacheKey.Token.Token));
}
entry.RegisterPostEvictionCallback((key, value, reason, state) =>
{
// 清理过期缓存键值
var k = key.ToString();
if (!string.IsNullOrEmpty(k))
{
Keys.Remove(k);
var item = Keys.LastOrDefault(item => item.Key == k);
if (item.Key != null)
{
Keys.Remove(item);
}
}
});
Keys.Add(cacheKey);
}
public void Clear(string? key)
{
throw new NotImplementedException();
if (!string.IsNullOrEmpty(key))
{
var cacheKey = Keys.LastOrDefault(item => item.Key == key);
if (cacheKey.Token != null)
{
cacheKey.Token.Cancel();
cacheKey.Token.Dispose();
}
Keys.Remove(cacheKey);
}
else
{
Init();
}
}
#region