数据库中某个表中的数据需要频繁访问,此时可以将其保存在cache中,表中数据变化时缓存自动变化。
此功能需.net FrameWork 2.0以上及MS Sql Server 2005以上。
要实现此功能,需要在三个级别上处理:数据库、.net配置文件、页面程序。
一、首先开启数据库缓存依赖功能,并确定数据库是否启用Service Broker。
aspnet_regsql -S <服务器名称> -U <登录账号>-P <登录密码> -d <数据库名称> -ed
执行Select DATABASEpRoPERTYEX('<数据库名称>','IsBrokerEnabled') 或 select is_broker_enabled from sys.databases where name='<数据库名称>'
结果1 表示Service Broker已经启用,0 表示没有启用
如果没有启用,执行ALTER DATABASE <数据库名称> SET ENABLE_BROKER
二、ASP.NET中配置
1、web.config配置:
<system.web>
<caching>
<sqlCacheDependency enabled="true" pollTime="1000">
<databases>
<add name="abico" connectionStringName="testCache"/>
</databases>
</sqlCacheDependency>
</caching>
</system.web>
<connectionStrings>
<add name="testCache" connectionString="data source=.;initial catalog = test;user id=sa ;password=sa" providerName="System.Data.SqlClient"/>
</connectionStrings>
2、Global.asax配置:
程序执行时需要设置SqlDependency为启动状态,此时放在Global.asax文件的Application_Start中执行:
void Application_Start(object sender, EventArgs e)
{
//在应用程序启动时运行的代码
System.Data.SqlClient.SqlDependency.Start(System.Configuration.ConfigurationManager.ConnectionStrings["testCache"].ToString());
}
void Application_End(object sender, EventArgs e)
{
//在应用程序关闭时运行的代码
System.Data.SqlClient.SqlDependency.Stop(System.Configuration.ConfigurationManager.ConnectionStrings["testCache"].ToString());
}
三、程序页面
protected void Page_Load(object sender, EventArgs e)
{
DataTable myDt = getDataTable();
GridView1.DataSource = myDt.DefaultView;
GridView1.DataBind();
}
private DataTable getDataTable()
{
DataTable dtCache = (DataTable)HttpRuntime.Cache["testCache"];
if (dtCache != null)
{
return dtCache;
}
else
{
string mySql = "select * from Table1";
SqlConnection myConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["testCache"].ToString());
if (myConn.State != ConnectionState.Open)
{
myConn.Open();
}
SqlCommand myCmd = new SqlCommand(mySql, myConn);
System.Web.Caching.SqlCacheDependency mySqlDep = new System.Web.Caching.SqlCacheDependency(myCmd);
SqlDataAdapter mySqlAdapter = new SqlDataAdapter(myCmd);
DataTable myDt = new DataTable();
mySqlAdapter.Fill(myDt);
if (myDt != null)
{
HttpRuntime.Cache.Insert("testCache", myDt, mySqlDep);
}
return myDt;
}
}