最近自己在写一个demo,想尝试一下缓存依赖,所以写下此文章,便于自己以后翻阅。首先我们先定义缓存的通用接口和实现该接口的类;
///
/// 定义cache的通用接口
///
public interface ICacheWrite
{
void AddCache(string key, object value, DateTime expDate);
void AddCache(string key, object value,CacheDependency obj, DateTime expDate);
void AddCache(string key, object value);
object GetCache(string key);
T GetCache
(string key);
object Delete(string key);
void SetCache(string key, object value, DateTime extDate);
void SetCache(string key, object value);
}
///
/// 缓存实现类,继承ICacheWrite
///
public class HttpRuntimeCacheWriter : ICacheWrite
{
public HttpRuntimeCacheWriter()
{
}
public void AddCache(string key, object value, DateTime expDate)
{
HttpRuntime.Cache.Insert(key, value, null, expDate, TimeSpan.Zero);
}
public void AddCache(string key, object value)
{
HttpRuntime.Cache.Insert(key, value);
}
public object GetCache(string key)
{
return HttpRuntime.Cache[key];
}
public T GetCache
(string key)
{
return (T)HttpRuntime.Cache[key];
}
public object Delete(string key)
{
return HttpRuntime.Cache.Remove(key);
}
public void SetCache(string key, object value, DateTime extDate)
{
HttpRuntime.Cache.Remove(key);
AddCache(key, value, extDate);
}
public void SetCache(string key, object value)
{
HttpRuntime.Cache.Remove(key);
AddCache(key, value);
}
///
/// 具有缓存依赖的
///
///
///
///
///
public void AddCache(string key, object value, CacheDependency obj, DateTime expDate)
{
HttpRuntime.Cache.Insert(key, value, obj, expDate, TimeSpan.Zero);
}
}
然后将数据加入到缓存中
public List<Navigation> GetNavigation()
{
HttpRuntimeCacheWriter http = new HttpRuntimeCacheWriter();
//先从缓存中获取数据
List<Navigation> list = http.GetCache("Navigation") as List<Navigation>;
if (list== null ||list.Count <0)
{
//缓存过期或更新,重新获取,在加入到缓存中
list = _Navigation.LoadEntities(p => p.Enable == 1).OrderBy(p => p.url).ToList();
http.AddCache("Navigation", list, new System.Web.Caching.SqlCacheDependency("Navigation", "Navigation"), DateTime.Now.AddMinutes(10));
}
return list;
}
<connectionStrings>
<add connectionString="Server=.;Database=Test.Demo.Mvc.DB;uid=sa;pwd=123456;" name="Navigation" providerName="System.Data.SqlClient" />
</connectionStrings>
在 <system.web>节点下配置缓存信息
<!--添加数据缓存节点-->
<caching>
<sqlCacheDependency enabled="true">
<databases>
<add name="Navigation" pollTime="5000" connectionStringName="Navigation" />
</databases>
</sqlCacheDependency>
</caching>
<!--添加数据缓存节点-->
注意:这里所有的name必须对应。
在Application_Start()中加入启用数据缓存的代码:
//启动数据库的数据缓存依赖功能
SqlCacheDependencyAdmin.EnableNotifications(connectionString);
//启用数据表缓存
SqlCacheDependencyAdmin.EnableTableForNotifications(connectionString, "Navigation");