缓存有多个依赖关系的数据

使用AggregateCacheDependency类将多个缓存依赖关系绑定在一起。 AggregateCacheDependency有一个Add方法,这个方法的参数是一个CacheDependency对象数组。这样就能编写代码,增加常规的CacheDependency,SqlCacheDependency,甚至定制CacheDependency,当这些依赖关系修改时,就会删除缓存的项。

例如,假如一个作者跟踪系统的数据取自一个包含版权信息的XML文件,还来自一个包含作者地址和联系方式信息的数据库。这些数据合并到一个DataSet中,由ASP.NET代码用来生成作者信息的一个网页。要确保页面很快地得到DataSet,一旦创建就将其放在缓存中。
首先为有版权信息的XML文件创建一个CacheDependency:
//  Make a dependency on the author royalties file
 
//  so if someone updates it, the cached data will
 
//  be disposed of.
string  file  =   this .Server.MapPath( " author_royalties.xml " );
  CacheDependency fileDep 
=   new  CacheDependency(file);

接下来,为数据库或者表创建一个
CacheDependency:
 // Use our method from 14.10 to make a SqlCacheDependency.
    SqlCacheDependency sqlDep = CreateSqlCacheDependency(connStr);  



然后创建一个DataSet引用,代码在缓存中查找这个数据集,如果缓存中还没有相应的DataSet,就会创建一个新的DataSet,填入数据库中的数据,然后填入XML文件中的数据:
//  Set up data table to get.
    DataSet authorInfo  =   null ;

    
//  Look for the pubs key in the cache.
    
//  If it isn't there, create it with a dependency
    
//  on a SQL Server table using the SqlCacheDependency class.
    
//  The "this" pointer refers to a Page class for a web page and
    
//  it accesses the System.Web.UI.Page.Cache property.
     if  ( this .Cache[ " authorInfo " ==   null )
    
{
        
// The data wasn't there so go get it and put it in the cache.
        authorInfo = new DataSet("AuthorInfo");
        
using (SqlConnection sqlConn = new SqlConnection(connStr))
        
{
            
using (SqlDataAdapter adapter =
                
new SqlDataAdapter("SELECT * FROM AUTHORS", sqlConn))
            
{
                adapter.Fill(authorInfo);

                
// Now add the royalty info.
                authorInfo.ReadXml(file, XmlReadMode.InferSchema);

  
 最后从CacheDependency(fileDep)和SqlCacheDependency(sqlDep)为这个DataSet创建一个
    AggregateCacheDependency 。这个DataSet增加到有 AggregateCacheDependency (aggDep)的缓存,从此以后,则由缓存负责管理DataSet。如果缓存中已经有一个DataSet,而且依赖关系尚未触发,就会从缓存中返回DataSet

                
// Make the aggregate dependency so that if either the
                
// db or file changes, we toss this out of the cache.
                AggregateCacheDependency aggDep = new AggregateCacheDependency();
                
// Add the two dependencies to the aggregate.
                aggDep.Add(new CacheDependency[] { sqlDep, fileDep });

                
// Add author info dataset to cache with the aggregate
                
// dependency so that if either changes the cache will refetch.
                this.Cache.Insert("authorInfo", authorInfo, aggDep);
            }

        }

    }

    
else
    
{
        authorInfo 
= (DataSet)this.Cache["authorInfo"];
    }






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值