using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Text;
namespace Mini.Common
{
public class CacheHelper
{
public static IMemoryCache _memoryCache = new MemoryCache(new MemoryCacheOptions());
///
/// 缓存绝对过期时间
///
///Cache键值
///给Cache[key]赋的值
///minute分钟后绝对过期
public static void CacheInsertAddMinutes(string key, object value, int minute)
{
if (value == null) return;
_memoryCache.Set(key, value, new MemoryCacheEntryOptions()
.SetAbsoluteExpiration(TimeSpan.FromMinutes(minute)));
}
///
/// 缓存相对过期,最后一次访问后minute分钟后过期
///
///Cache键值
///给Cache[key]赋的值
///滑动过期分钟
public static void CacheInsertFromMinutes(string key, object value, int minute)
{
if (value == null) return;
_memoryCache.Set(key, value, new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromMinutes(minute)));
}
///
///以key键值,把value赋给Cache[key].如果不主动清空,会一直保存在内存中.
///
///Cache键值
///给Cache[key]赋的值
public static void Set(string key, object value)
{
_memoryCache.Set(key, value);
}
///
///清除Cache[key]的值
///
///
public static void Remove(string key)
{
_memoryCache.Remove(key);
}
///
///根据key值,返回Cache[key]的值
///
///
public static object CacheValue(string key)
{
return _memoryCache.Get(key);
}
///
/// 获取缓存
///
/// 类型
/// Key
///
public static T Get(string key)
{
try
{
T t = (T)_memoryCache.Get(key);
return t;
}
catch (Exception ex)
{
throw ex;
}
}
}
}