c# .net 程序级 缓存,可设置缓存对象的到期时间,到期后缓存key为空
一、缓存帮助类
CacheHelp.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Caching;
namespace CacheWeb
{
public class CacheHelp
{
/// <summary>
/// 缓存指定对象,设置缓存
/// </summary>
/// <param name="key">缓存的key</param>
/// <param name="value">缓存的值</param>
/// <param name="Seconds">设置缓存时间;单位:秒</param>
/// <returns></returns>
public static bool Set(string key, object value,double Seconds)
{
return Set(key, value, null, DateTime.Now.AddSeconds(Seconds), Cache.NoSlidingExpiration,
CacheItemPriority.Default, null);
}
/// <summary>
/// 缓存指定对象,设置缓存
/// </summary>
public static bool Set(string key, object value, string path)
{
try
{
var cacheDependency = new CacheDependency(path);
return Set(key, value, cacheDependency);
}
catch
{
return false;
}
}
/// <summary>
/// 缓存指定对象,设置缓存
/// </summary>
public static bool Set(string key, object value, CacheDependency cacheDependency)
{
return Set(key, value, cacheDependency, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,
CacheItemPriority.Default, null);
}
/// <summary>
/// 缓存指定对象,设置缓存
/// </summary>
public static bool Set(string key, object value, double seconds, bool isAbsulute)
{
return Set(key, value, null, (isAbsulute ? DateTime.Now.AddSeconds(seconds) : Cache.NoAbsoluteExpiration),
(isAbsulute ? Cache.NoSlidingExpiration : TimeSpan.FromSeconds(seconds)), CacheItemPriority.Default,
null);
}
/// <summary>
/// 获取缓存对象
/// </summary>
public static object Get(string key)
{
return GetPrivate(key);
}
/// <summary>
/// 判断缓存中是否含有缓存该键
/// </summary>
public static bool Exists(string key)
{
return (GetPrivate(key) != null);
}
/// <summary>
/// 移除缓存对象
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static bool Remove(string key)
{
if (string.IsNullOrEmpty(key))
{
return false;
}
HttpRuntime.Cache.Remove(key);
return true;
}
/// <summary>
/// 移除所有缓存
/// </summary>
/// <returns></returns>
public static bool RemoveAll()
{
IDictionaryEnumerator iDictionaryEnumerator = HttpRuntime.Cache.GetEnumerator();
while (iDictionaryEnumerator.MoveNext())
{
HttpRuntime.Cache.Remove(Convert.ToString(iDictionaryEnumerator.Key));
}
return true;
}
/// <summary>
/// 尝试获取缓存,不存在则执行匿名委托
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="func"></param>
/// <param name="Seconds">设置缓存时间;单位:秒</param>
/// <returns></returns>
public static T TryGet<T>(string key, Func<T> func, double Seconds)
{
if (Exists(key)) return (T)Get(key);
var result = func.Invoke();
Set(key, result, Seconds);
return result;
}
/// <summary>
/// 设置缓存
/// </summary>
public static bool Set(string key, object value, CacheDependency cacheDependency, DateTime dateTime,
TimeSpan timeSpan, CacheItemPriority cacheItemPriority, CacheItemRemovedCallback cacheItemRemovedCallback)
{
if (string.IsNullOrEmpty(key) || value == null)
{
return false;
}
HttpRuntime.Cache.Insert(key, value, cacheDependency, dateTime, timeSpan, cacheItemPriority,
cacheItemRemovedCallback);
return true;
}
/// <summary>
/// 获取缓存
/// </summary>
private static object GetPrivate(string key)
{
return string.IsNullOrEmpty(key) ? null : HttpRuntime.Cache.Get(key);
}
}
}
二、程序使用
1、简单的数据缓存
string SetCacheStatusMsg = "初始数据";
string CacheKey = "CacheKeyTest";
string EasyCacheData = null;
if (!CacheHelp.Exists(CacheKey))
{
#region 增加缓存
EasyCacheData = "测试的数据";
bool SetCacheStatus = CacheHelp.Set(
key: CacheKey,
value: EasyCacheData,
Seconds: 60 //缓存时长,单位“秒”
);
if (SetCacheStatus)
{
SetCacheStatusMsg = "增加缓存成功";
}
else
{
SetCacheStatusMsg = "增加缓存失败";
}
#endregion
}
else {
#region 获取缓存
EasyCacheData = CacheHelp.Get(CacheKey).ToString();
#endregion
}
ViewBag.EasyCacheData = EasyCacheData;
2、“泛型”数据缓存
string CacheKeyUserList = "CacheKeyUserList";
List<UserInfoModel> ListCacheData = null;
if (!CacheHelp.Exists(CacheKeyUserList))
{
#region 增加缓存
//造数据(可以直接数据库访问获得数据)
List<UserInfoModel> list = new List<UserInfoModel>();
for (int i = 1; i < 6; i++)
{
UserInfoModel userinfo = new UserInfoModel();
userinfo.ID = i;
userinfo.name = "小明" + i + "号";
list.Add(userinfo);
}
ListCacheData = list;
bool SetCacheStatus = CacheHelp.Set(
key: CacheKeyUserList,
value: list,
Seconds: 60 //缓存时长,单位“秒”
);
if (SetCacheStatus)
{
SetCacheStatusMsg = "增加缓存成功";
}
else
{
SetCacheStatusMsg = "增加缓存失败";
}
#endregion
}
else
{
#region 获取缓存
ListCacheData = (List<UserInfoModel>)CacheHelp.Get(CacheKeyUserList);
#endregion
}
ViewBag.ListCacheData = ListCacheData;
三、视图使用
@using CacheWeb.Controllers;
@{
ViewBag.Title = "Home Page";
}
<div class="jumbotron">
<h3>简单的数据缓存 【EasyCacheData】</h3>
<p class="lead"> @ViewBag.EasyCacheData </p>
</div>
<div class="jumbotron">
<h3>二、“泛型”数据缓存 【ListCacheData】</h3>
@{
foreach (UserInfoModel item in (List<UserInfoModel>)ViewBag.ListCacheData)
{
<p class="lead"> ID: @item.ID | Name:@item.name</p>
}
}
</div>