c# 数据库缓存依赖

1.为缓存依赖项启动通知数据库

在vs开发人员命令提示中运行(切换到aspnet_regsql.exe所在目录,示例目录:C:WindowsMicrosoft.NETFramework64v4.0.30319):

   aspnet_regsql -S .  -U sa -P pwd -ed -d xxx  -et -t xxx;

缓存依赖禁用:

  aspnet_regsql -S . ds -E -dd -d XXX

  -S服务器名称 -E集成身份验证 -U 账号 -P 密码  -ed为sql缓存依赖项创建数据库 -dd禁用  -d数据库名称 -et 为sql缓存启动表   -t表名

2.配置web.config文件

在system.web下添加

   <caching>
        <sqlCacheDependency enabled="true">
          <databases>
            <add name="practiceDB" connectionStringName="constring" pollTime="500"/> 
          </databases>
        </sqlCacheDependency>
      </caching>

  然后在configuration下添加对应的键值

  <add name="constring" constring="server=ZMING-PCMING;Initial Catalog=practiceDB;User ID=sa;Password=qwertyuiop"/> 

 

3.插入有数据库依赖项的缓存

 if (Cache["key"] == null)
            {
                nmdb.DataClassesDataContext db = new nmdb.DataClassesDataContext();
                var r = (from res in db.t1 select res).ToList();
                Cache.Insert("key", r, new SqlCacheDependency("practiceDB", "student"));
               
            }
            Repeater1.DataSource = Cache["key"];
            Repeater1.DataBind();

  大功告成。每次数据库没改变的时候就会直接访问缓存,这点可以在Sql server profiler中确认。只有当改变数据库中的数据时候才会重新去请求数据库再去拿去数据

There are two ways of constructing a software design.One is to make it so simple that there are obviously no deficiencies;the other is to make it so complicated that there are no obvious deficiencies.
原文地址:https://www.cnblogs.com/yuanjunqq/p/5737120.html