1 web.config配置如下;
<caching>
<!--enabled指示是否轮询更改。pollTime此值对应于连续两次轮询之间的毫秒数。不能设置为小于 500 毫秒的值。默认值为 1 分钟。-->
<sqlCacheDependency enabled="true" pollTime="60000">
<databases>
<add name="EduPortalCache" connectionStringName="EduPortalConn" />
</databases>
</sqlCacheDependency>
</caching>
<connectionStrings>
<add name="EduPortalConn" connectionString="User ID=sa;Initial Catalog=Portal;Data Source=localhost;Password=1111" providerName="System.Data.SqlClient" />
</connectionStrings>
2 打开 Visual Studio 2008 命令提示 执行如下命令:
aspnet_regsql -C "User ID=sa;Initial Catalog=Portal;Data Source=localhost;Password=1111" -ed -et -t "SSOPortal_PublishNewTrends"
aspnet_regsql -C "User ID=sa;Initial Catalog=Portal;Data Source=localhost;Password=1111" -ed -et -t "SSOPortal_PublishRecommendation"
查看那些表使用了缓存依赖
aspnet_regsql -C "User ID=sa;Initial Catalog=Portal;Data Source=localhost;Password=1111" –lt
3 代码如下:
/// <summary> /// 获取当前应用程序指定CacheKey的Cache对象值 /// </summary> /// <param name="CacheKey">索引键值</param> /// <returns>返回缓存对象</returns> public static object GetCache(string CacheKey) { System.Web.Caching.Cache objCache = HttpRuntime.Cache; return objCache[CacheKey]; } /// <summary> /// 设置以缓存依赖的方式缓存数据 /// </summary> /// <param name="CacheKey">索引键值</param> /// <param name="objObject">缓存对象</param> /// <param name="cacheDepen">依赖对象</param> public static void SetCache(string CacheKey, object objObject, System.Web.Caching.CacheDependency dep) { System.Web.Caching.Cache objCache = HttpRuntime.Cache; objCache.Insert( CacheKey, objObject, dep, System.Web.Caching.Cache.NoAbsoluteExpiration,//从不过期 System.Web.Caching.Cache.NoSlidingExpiration,//禁用可调过期 System.Web.Caching.CacheItemPriority.Default, null); }
/// <summary> /// 绑定最新动态 /// </summary> private void BindNews() { //EduPortal.BLL.SSOPortal_PublishNewTrends bll = new EduPortal.BLL.SSOPortal_PublishNewTrends(); //DataSet ds = bll.GetList(8, "", "OrdID DESC"); //repNews.DataSource = ds.Tables[0]; string CacheKey = "SSONEWS"; object objModel = CommonHelper.GetCache(CacheKey);//从缓存中获取 if (objModel == null)//缓存里没有 { objModel = GetNews();//从数据库中获取 if (objModel != null) { //依赖数据库SSOPortal_PublishNewTrends表变化 来更新缓存 System.Web.Caching.SqlCacheDependency dep = new System.Web.Caching.SqlCacheDependency("EduPortalCache", "SSOPortal_PublishNewTrends"); CommonHelper.SetCache(CacheKey, objModel, dep);//写入缓存 } } repNews.DataSource = (DataTable)objModel; repNews.DataBind(); } /// <summary> /// 获取最新动态 /// </summary> /// <returns></returns> private DataTable GetNews() { DataTable dt = null; try { EduPortal.BLL.SSOPortal_PublishNewTrends bll = new EduPortal.BLL.SSOPortal_PublishNewTrends(); DataSet ds = bll.GetList(8, "", "OrdID DESC"); if (ds != null && ds.Tables[0].Rows.Count > 0) { dt = ds.Tables[0]; } } catch (Exception ex) { logger.Error(string.Format("操作类型:{0} 操作内容:{1} 操作用户:{2} 客户端IP:{3} 操作时间:{4} ", "最新动态", "最新动态-异常信息:" + ex.Message.ToString(), "", CommonHelper.GetIPAddress(), DateTime.Now.ToLocalTime())); } return dt; }
4 参考文章