在大型门户网站上大量的应用了缓存,缓存就是将页面数据存储到内存空间中,在浏览器请求页面时不用经历页面生命周期直接从缓存中读取数据并返回给浏览器,缓存有页面缓存、数据源缓存、数据缓存等,这里主要介绍数据库缓存依赖
数据库缓存依赖
TableName:表名称
以下命令在cmd下执行(进入:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727中)
注册依赖aspnet_regsql -S . -E -ed -dDataBaseName -et -t TableName
删除注册:aspnet_regsql -S . -E -d DataBaseName -dt -t TableName
取消依赖:aspnet_regsql -S . -E -dd DataBaseName
列出已注册表:aspnet_regsql -S . -E -d DataBaseName –lt
2.在web.config配置文件中新增如下配置节点
<system.web>
<caching>
<sqlCacheDependency enabled="true">
<databases>
<add name="GSSMS" connectionStringName="conStr2" pollTime="15000"/>
</databases>
</sqlCacheDependency>
</caching>
示例代码:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.Caching; using System.IO; using System.Data; using System.Text; public partial class 缓存_基于数据库的缓存依赖 : System.Web.UI.Page { protected void Page_Load(object sender,EventArgs e) { //ASPNETCaCheHelpers.CaCheHelper cache = new ASPNETCaCheHelpers.CaCheHelper(); //cache.Cacheobj = Cache; //检查缓存是否为空 if (Cache["newcache"] == null) { string filepath = Server.MapPath("Cache.txt"); //缓存依赖对象 sqlCacheDependency cachedependency = new sqlCacheDependency("GSMMS","T_Msg_CahceVersion"); //添加缓存 Cache.Add("newcache",GetMsg(),cachedependency,Cache.NoAbsoluteExpiration,Cache.NoSlidingExpiration,CacheItemPriority.Normal,CahceRemoveCallBack); //cache.AddDataBaseCacheDependency("newcache","GSMMS","T_Msg_CahceVersion",CahceRemoveCallBack); Response.Write(Cache["newcache"].ToString()); label1.Text = "从数据库中取数据再存到缓存中"; } else { Response.Write(Cache["newcache"].ToString()); label1.Text = "直接从缓存中拿数据"; } } //当缓存被删除时执行的方法(委托) private void CahceRemoveCallBack(string key,object value,CacheItemRemovedReason reason) { string filepath = Server.MapPath("CahceDataBaseDependency.txt"); string msg = "缓存:" + key + "被删除了,因为:" + reason.ToString() + "\r\n"; File.AppendAllText(filepath,msg); } private string GetMsg() { DataTable dt = sqlHelper_MSsql.sqlHelper.ExcuteDataTable("select * from T_Msg_CacheTest"); StringBuilder sb = new StringBuilder(); for (int i = 0; i < dt.Rows.Count; i++) { DataRow dr = dt.Rows[i]; sb.Append("<div>标题:" + dr["title"].ToString() + "---内容:" + dr["contents"].ToString() + "--添加时间:" + dr["addtime"].ToString() + "</div>"); } return sb.ToString(); } }