先上代码:
Code:
private void BindPageData()
{
DataTable dt = (DataTable)HttpRuntime.Cache["Category"];
if (dt == null)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand comm = new SqlCommand("select CategoryId,Name,Descn from Category", con);
SqlDataAdapter sda = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
sda.Fill(ds);
dt = ds.Tables[0];
SqlCacheDependency dep = new SqlCacheDependency("MSPetShop4", "Category");
AggregateCacheDependency aggCd = new AggregateCacheDependency();
aggCd.Add(dep);
HttpRuntime.Cache.Add("Category", dt, aggCd, System.DateTime.Now.AddHours(1), Cache.NoSlidingExpiration, CacheItemPriority.High, null);
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
然后再看配置文件:
Code:
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=192.168.2.55;Initial Catalog=MSPetShop4;Persist Security Info=True;User Id=sa;PassWord=sa" providerName="System.Data.SqlClient"/>
</connectionStrings>
<caching>
<sqlCacheDependency enabled="true" pollTime="500">
<databases>
<add name="MSPetShop4" connectionStringName="ConnectionString" pollTime="10000"/>
</databases>
</sqlCacheDependency>
</caching>
[1]当然注意引用 :
using System.Data.SqlClient;
using System.Web.Caching;
[2]
SqlCacheDependency dep = new SqlCacheDependency("MSPetShop4", "Category");
将库与表名建立数据缓存关系;
AggregateCacheDependency aggCd = new AggregateCacheDependency();
建立缓存依赖;
HttpRuntime.Cache.Add()函数中的参数有些地方需要注意:
缓存失效的时间.当然也可以永不失效(Cache.NoAbsoluteExpiration);
[3]
注意此处的Cache来自HttpRuntime类,而非PAGE
[4]
注意数据库连接字符串配置地方是在<connectionStrings>节点中;
pollTime是数据库轮询时间(以毫秒为单位)。 如果数据库数据更新频繁,些值不能太大;
暂时这第着;有空了写个像PetShop4中那样层次分明的缓存机制;
[5]
加上AJAX定时更新,使用数据缓存功能;
Code:
function $(obj)
{
return document.getElementById(obj);
}
function ReLoadData()
{
var tablelist=$('GridView1');
var values = TestAjaxData.BindPageData().value;
if(values!=null)
{
var rowLen=tablelist.rows.length;
tablelist.rows[0].cells[0].innerHTML=values.Columns[0].Name;
tablelist.rows[0].cells[1].innerHTML=values.Columns[1].Name;
tablelist.rows[0].cells[2].innerHTML=values.Columns[2].Name;
for(var i=1;i<rowLen-1;i++)
{
for(var x=0;x<3;x++)
{
if(tablelist.rows[i].cells[x].innerHTML!=values.Rows[i-1][values.Columns[x].Name])
{
SetBorderColor(tablelist,i,x);
window.setTimeout(ClearBorderColor(tablelist,i,x),2000);
tablelist.rows[i].cells[x].innerHTML=values.Rows[i-1][values.Columns[x].Name];
}
}
}
}
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
$("time").innerText= h + ":" + m + ":" + s;
}
ReLoadData();
window.setInterval(ReLoadData,5000);
function ClearBorderColor(obj,irow,icell){
return function(){
obj.rows[irow].cells[icell].style.setAttribute("border","0");
}
}
function SetBorderColor(obj,irow,icell){
obj.rows[irow].cells[icell].style.setAttribute("border","1px solid red");
}
当然相应的修改一个AJAX请求的数据函数
[AjaxMethod]
public DataTable BindPageData()在函数中不需要数据绑定.