首页 > 编程 > .NET > 正文

.net如何使用Cache框架给程序添加Cache

2024-07-10 12:49:02
字体:
来源:转载
供稿:网友

NET 4.0中新增了一个System.Runtime.Caching的名字空间,它提供了一系列可扩展的Cache框架,本文就简单的介绍一下如何使用它给程序添加Cache。

一个Cache框架主要包括三个部分:ObjectCache、CacheItemPolicy、ChangeMonitor。

ObjectCache表示一个CachePool,它提供了Cache对象的添加、获取、更新等接口,是Cache框架的主体。它是一个抽象类,并且系统给了一个常用的实现——MemoryCache。
CacheItemPolicy则表示Cache过期策略,例如保存一定时间后过期。它也经常和ChangeMonitor一起使用,以实现更复杂的策略。
ChangeMonitor则主要负责CachePool对象的状态维护,判断对象是否需要更新。它也是一个抽象类,系统也提供了几个常见的实现:CacheEntryChangeMonitor、FileChangeMonitor、HostFileChangeMonitor、SqlChangeMonitor。

1、首先新建一个一般控制程序,添加一个类,其中代码如下

#region class MyCachePool  {    ObjectCache cache = MemoryCache.Default;    const string CacheKey = "TestCacheKey";  //定义字符串类型常量CacheKey并赋初值为TestCacheKey,那么不能再改变CacheKey的值   //如执行CacheKey="2"; 就会运行错误在整个程序中 a的值始终为TestCacheKey    public string GetValue()    {      var content = cache[CacheKey] as string;      if(content == null)      {        Console.WriteLine("Get New Item");     //SlidingExpiration = TimeSpan.FromSeconds(3)        //第一种过期策略,当对象3秒钟内没有得到访问时,就会过期。如果对象一直被访问,则不会过期。        AbsoluteExpiration = DateTime.Now.AddSeconds(3)        //第二种过期策略,当超过3秒钟后,Cache内容就会过期。        content = Guid.NewGuid().ToString();        cache.Set(CacheKey, content, policy);      }      else      {        Console.WriteLine("Get cached item");      }      return content;    }#endregion

再在主程序入口

 static void Main(string[] args) {  MyCachePool pool = new MyCachePool();  MyCachePool1 pool1 = new MyCachePool1();  while(true)  {    Thread.Sleep(1000);    var value = pool.GetValue();    //var value = pool1.myGetValue();    Console.WriteLine(value);    Console.WriteLine(); }}

这个例子创建了一个保存3秒钟Cache:三秒钟内获取到的是同一个值,超过3秒钟后,数据过期,更新Cache,获取到新的值。

过期策略:

从前面的例子中我们可以看到,将一个Cache对象加入CachePool中的时候,同时加入了一个CacheItemPolicy对象,它实现着对Cache对象超期的控制。例如前面的例子中,我们设置超时策略的方式是:AbsoluteExpiration = DateTime.Now.AddSeconds(3)。它表示的是一个绝对时间过期,当超过3秒钟后,Cache内容就会过期。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表