Files
RBMESAPICore/Context/CacheHelper.cs
yuyubohh e8494ba988 qqq
2025-09-09 22:41:29 +08:00

67 lines
1.9 KiB
C#

using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
namespace RB_MES_API.Context
{
/// <summary>
/// 缓存处理
/// </summary>
public class CacheHelper
{
//public CacheHelper Defalut=new CacheHelper();
private static IMemoryCache _cache =new MemoryCache(new MemoryCacheOptions());
/// <summary>
/// 读取缓存
/// </summary>
/// <param name="cacheKey"></param>
/// <returns></returns>
public static T GetCache<T>(string cacheKey)
{
if(string.IsNullOrEmpty(cacheKey))
{
throw new ArgumentNullException(nameof(cacheKey));
}
T cache;
_cache.TryGetValue(cacheKey, out cache);
return cache;
}
/// <summary>
/// 设置缓存(滑动过期)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key">关键字</param>
/// <param name="value">缓存值</param>
public static void Set_AbsluteExpire<T>(string key,T value)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException(nameof(key));
}
T v;
if(_cache.TryGetValue(key, out v))
{
_cache.Remove(key);
}
_cache.Set(key, value, TimeSpan.FromMinutes(20));
}
/// <summary>
/// 移除缓存
/// </summary>
/// <param name="key"></param>
public static void Remove(string key)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException(nameof(key));
}
_cache.Remove(key);
}
public void Dispose()
{
if(_cache != null) { _cache.Dispose(); }
GC.SuppressFinalize(this);
}
}
}