105 lines
3.2 KiB
C#
105 lines
3.2 KiB
C#
using Microsoft.Extensions.Caching.Memory;
|
|
|
|
namespace YLErp.Providers
|
|
{
|
|
/// <summary>
|
|
/// MemoryCacheProvider
|
|
/// </summary>
|
|
public class MemoryCacheProvider : YLErp.Abstract.ICacheProvider
|
|
{
|
|
readonly MemoryCache _cache;
|
|
|
|
public MemoryCacheProvider()
|
|
{
|
|
_cache = new MemoryCache(new MemoryCacheOptions());
|
|
}
|
|
|
|
public void FlushAll()
|
|
{
|
|
lock (_cache)
|
|
{
|
|
_cache.Compact(1);
|
|
_cache.Compact(1);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 检索指定的项
|
|
/// </summary>
|
|
public object Get(string key)
|
|
{
|
|
return _cache.Get(key);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 检索指定的项
|
|
/// </summary>
|
|
public T Get<T>(string key)
|
|
{
|
|
var obj = _cache.Get(key);
|
|
|
|
if (obj != null)
|
|
{
|
|
return (T)obj;
|
|
}
|
|
|
|
return default;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 设置缓存对象
|
|
/// </summary>
|
|
/// <param name="key">用于引用该对象的缓存密钥</param>
|
|
/// <param name="value">要插入缓存中的对象</param>
|
|
/// <param name="absoluteExpiration">从该处插入的对象过期并从缓存中删除的时间</param>
|
|
public void Set(string key, object value, DateTimeOffset absoluteExpiration)
|
|
{
|
|
_cache.Set(key, value, absoluteExpiration);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 设置缓存对象
|
|
/// </summary>
|
|
/// <param name="key">用于引用该对象的缓存密钥</param>
|
|
/// <param name="value">要插入缓存中的对象</param>
|
|
/// <param name="absoluteExpirationRelativeToNow">
|
|
/// 对象的到期时间和上次访问所插入的对象的时间之间的间隔。 如果此值为 20 分钟的等效项,该对象会过期,可从缓存中删除上次访问后的 20 分钟。
|
|
/// </param>
|
|
public void Set(string key, object value, TimeSpan absoluteExpirationRelativeToNow)
|
|
{
|
|
_cache.Set(key, value, absoluteExpirationRelativeToNow);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 设置缓存对象
|
|
/// </summary>
|
|
/// <param name="key">用于引用该对象的缓存密钥</param>
|
|
/// <param name="value">要插入缓存中的对象</param>
|
|
/// <param name="slidingExpiration">
|
|
/// 对象的到期时间和上次访问所插入的对象的时间之间的间隔。 如果此值为 20 分钟的等效项,该对象会过期,可从缓存中删除上次访问后的 20 分钟。
|
|
/// </param>
|
|
public void SetWithSlidingExpiration(string key, object value, TimeSpan slidingExpiration)
|
|
{
|
|
_cache.Set(key, value, new MemoryCacheEntryOptions
|
|
{
|
|
SlidingExpiration = slidingExpiration
|
|
});
|
|
}
|
|
|
|
/// <summary>
|
|
/// 删除指定的项
|
|
/// </summary>
|
|
public void Remove(string key)
|
|
{
|
|
_cache.Remove(key);
|
|
}
|
|
|
|
public static readonly MemoryCacheProvider Default;
|
|
|
|
static MemoryCacheProvider()
|
|
{
|
|
Default = new MemoryCacheProvider();
|
|
}
|
|
}
|
|
}
|