数据库依赖缓存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:\WINDOWS\Microsoft.NET\Framework\ 找到相应.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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值