EnterpriseLibrary 3.0的缓存应用程序块

    为什么使用缓存,缓存能为您的应用程序带来那些好处这里不在描述,不知道的朋友可以google一下,我们直接将如何通过使用Enterprise Library来方便的缓存,获取您的数据!
      首先我们在配置文件中配置缓存策略,可以使用Enterprise Library配置工具方便的配置,下面介绍的方法和截图都是使用3.0的配置工具来说明。
      1)用配置工具打开配置文件,右键点击Application Configuration,点击new,CachingApplicationBlock,配置工具会自动增加一个默认Cache Manager 配置节点。
   2)点击Caching Application Block节点,改变默认属性名,如果你的代码没有指定一个特别cache manager,将使用该默认节点,也可以将Caching Application Block的DefaultCacheManager的属性设置为你想默认的节点名。
   3)在第二步中我们将cache manager节点命名为UserCache,我们可以在该节点有3个属性:
      ExpirationPollFrequencyInSeconds:多少秒进行一次过期检查,缺省值60秒
      MaximumElementsInCacheBeforeScavenging:最多可以缓存对象数,超过这个个数,则触发清除事件,缺省值 1000
      NumberToRemoveWhenScavenging:每次清除缓存项时候,按照优先级,清除掉优先级低的多少项

      默认缓存项备份存储在内存中,你还可以指定将其存储在数据库中,或新的独立空间,这个我们放在后面讲。下面我们就看看在程序中如何使用配置好的缓存

//添加引用
using Microsoft.Practices.EnterpriseLibrary.Caching;
using Microsoft.Practices.EnterpriseLibrary.Caching.Expirations;

Guid id
=Guid.NewGuid();
//建立缓存工厂,从配置文件中读取缓存策略。
CacheManager weuserCache = CacheFactory.GetCacheManager();
//添加缓存:其中第三个参数为缓存优先级,第4个参数为过期设置,过期时间表达式。
weuserCache.Add(id.ToString(), "Young.CSharper", CacheItemPriority.Normal, nullnew SlidingTime(TimeSpan.FromMinutes(1)));
//读取缓存,注意转化类型。
string name = weuserCache.GetData(id.ToString()).ToString();
//移除某一个缓存项。
weuserCache.Remove(id.ToString());
//移除所有缓存项。
weuserCache.Flush();

时间的过期策略
,支持两种相对时间和绝对时间。
1:指定单一的时间作为过期:
//表达式的格式:<Minute> <Hour> <Day of month> <Month> <Day of week>
//“* * * * *”     每分钟
//“5 * * * *”    每个小时的第5分钟
DateTime refreshTime = new DateTime(20051112125130);
AbsoluteTime expireTime 
= new AbsoluteTime(refreshTime);
weuserCache.Add(id.ToString(), 
"Young.CSharper", CacheItemPriority.Normal, null, expireTime);
2.变化的时间:
//访问5分钟后过期
//TimeSpan refreshTime = new TimeSpan(0, 5, 0);
//SlidingTime expireTime = new SlidingTime(refreshTime);
weuserCache.Add(id.ToString(), "Young.CSharper", CacheItemPriority.Normal, null, expireTime);
posted @ 2007-05-09 22:11  Young.Jiang  阅读(608)  评论(1编辑  收藏  举报