提示:C# 中使用Cache缓存数据
private static MemoryCache cache = new MemoryCache(new MemoryCacheOptions());
//获取缓存值
///key:缓存对应的键值
public static object GetCacheValue(string key)
{
object val = null;
if (key != null && cache.TryGetValue(key, out val))
{
return val;
}
else
{
return default(object);
}
}
//设置缓存值(默认缓存时间)
public static void SetChacheValue(string key, object value)
{
if (key != null)
{
cache.Set(key, value, new MemoryCacheEntryOptions
{
SlidingExpiration = TimeSpan.FromHours(1)
});
}
}
//设置缓存值(可自己修改缓存时间)
public static void SetChacheValue(string key, object value, int second)
{
if (key != null)
{
cache.Set(key, value, TimeSpan.FromSeconds(second));
}
}
//是否存在某缓存值
public static bool Exists(string key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
return cache.TryGetValue(key, out _);
}
//删除缓存值
public static void Remove(string key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
cache.Remove(key);
}