缓存数据库表

使用SqlCacheDependency类,从而在底层数据改变时使缓存中的数据到期。SqlCacheDependency建立了缓存与数据库的一个关系,如果数据库的数据发生了改变,有这样依赖的缓存中的项将从缓存中释放,原先建立这个缓存项的代码可以在此从数据库获取值。

为了说明这一点,下面使用CreateSqlCacheDependency方法为Microsoft  SQL  Server中pubs数据库的Authors表创建一个SqlCacheDependency对象,pubs数据库是一个随SQL  Server2000发行的事例数据库:
public  SqlCacheDependency CreateSqlCacheDependency( string  connStr)
    
{
        
// Make a dependency on the authors database table so that
        
// if it changes, the cached data will also be disposed of.

        
// Make sure we are enabled for notifications for the db.
        
// Note that the parameter has to be the actual connection
        
// string NOT the connection string NAME from web.config.
        SqlCacheDependencyAdmin.EnableNotifications(connStr);

        
// Make sure we are enabled for notifications for the table.
        SqlCacheDependencyAdmin.EnableTableForNotifications(connStr, "Authors");

        
// This is case-sensitive so make sure the first entry
        
// matches the entry in the web.config file exactly.
        
// The first parameter here must be the connection string
        
// NAME not the connection string itself…
        return new SqlCacheDependency("pubs""Authors");
    }

 
SqlCacheDependencyAdmin类负责与SQL Server通信,建立必要的基础设施。以便
qlCacheDependency
正确的触发。在应用web.config文件中configuration/system.web/caching下有一部分定义了SqlC
acheDependency 依赖性基于哪些参数操作。对于轮询时间(仅适用于SQL Server 2000,因为SQL Server 2005不会轮询)和连接时间有一些超时设置,另外还有一个指向连接串的链接,从而可以连接串名来使用连接串,这个 连接可以在web.config中配置,如下所示

< caching >
         
< sqlCacheDependency  enabled ="True"  pollTime ="60000" >
            
< databases >
              
< add  name ="pubs"  connectionStringName ="LocalPubs"  pollTime ="9000000"   />
            
</ databases >
         
</ sqlCacheDependency >
  
</ caching >

  
< connectionStrings >
        
< add  name ="LocalPubs"  connectionString ="Server=(local);Integrated     
        Security=True;Database=pubs;Persist Security Info=True"

          providerName
="System.Data.SqlClient" />
  
</ connectionStrings >

使用SqlCacheDependency类时,首先要确保已经对数据库和所监视的表启用了通知(代码中紫色字体),如果对数据库或者数据库表未启用通知,构造
SqlCacheDependency时就会抛出( DatabaseNotEnabledForNotificationException )异常。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值