数据库依赖缓存SqlCacheDependency使用

    当使用ASP.NET的Cache缓存数据库中数据时,可以使用SqlCacheDependency设置当表中数据改变时更新缓存。

    1.设置web.config

       

<configuration>
    <connectionStrings>
    <add name="Northwind" connectionString="Data Source=.;Initial Catalog=Northwind;User ID=sa;Password=sa;" providerName="System.Data.SqlClient"/>
 </connectionStrings>
 <system.web>
        <compilation debug="true" targetFramework="4.0"/>
   <caching>
     <sqlCacheDependency enabled="true" pollTime="60000">
       <databases>
         <add name="northwind" connectionStringName="Northwind" pollTime="90000"/>
       </databases>
     </sqlCacheDependency>
   </caching>
    </system.web>
</configuration>
View Code

    2.在C:WINDOWSMicrosoft.NETFramework 找到相应.net版本对应目录下的aspnet_regsql.exe,在命令行中执行如下命令:

       aspnet_regsql -C "data source=127.0.0.1;initial catalog=Northwind;user id=sa;password=sa;" -ed -et -t "test"

       其中test为数据库中要缓存的表名。会在数据库中生成一个名为AspNet_SqlCacheTablesForChangeNotification的表。

   3.代码实现

     

public DataTable SetCache()
    {
        DataTable dt;
        SqlCacheDependency SqlDep = null;
        if (Cache.Get("cachekey") != null)
        {
            dt = HttpRuntime.Cache.Get("northwind") as DataTable;
        }
        else
        {
            dt = DataHelper.GetAllData();
            try
            {
                SqlDep = new SqlCacheDependency("northwind", "test");
                HttpRuntime.Cache.Insert("cachekey", dt, SqlDep);
            }
            catch(Exception ex)
            {
            }
        }
        return dt;
    }
View Code

     其中SqlDep = new SqlCacheDependency("northwind", "test"); 中的第一个参数对应的是web.config中添加的 <add name="northwind" connectionStringName="Northwind" pollTime="90000"/> 中的name,test为表名。

   

原文地址:https://www.cnblogs.com/CodePastry/p/3544645.html