使用.net的ObjectCacheCache框架快速实现Cache操作
.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。
如下是一个简单的示例:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.Caching; using System.Threading; using System.IO; namespace CacheTest { class Program { static void Main(string[] args) { MyCachePool.Test(); Console.ReadKey(); } } class MyCachePool { ObjectCache cache = MemoryCache.Default; const string CacheKey = "TestCacheKey"; public string GetValue() { var content = cache[CacheKey] as string; if (content == null) { Console.WriteLine("Get New Item"); //绝对时间,3秒过期 var policy = new CacheItemPolicy() { AbsoluteExpiration = DateTime.Now.Add(TimeSpan.FromSeconds(3)) }; content = Guid.NewGuid().ToString(); cache.Set(CacheKey, content, policy); } else { Console.WriteLine("Get cached item"); } return content; } public static void Test() { var cachePool = new MyCachePool(); while (true) { Thread.Sleep(1000); var value = cachePool.GetValue(); Console.WriteLine(value); Console.WriteLine(); } } } }

这个例子创建了一个保存3秒钟Cache:三秒钟内获取到的是同一个值,超过3秒钟后,数据过期,更新Cache,获取到新的值。
过期策略:
从前面的例子中我们可以看到,将一个Cache对象加入CachePool中的时候,同时加入了一个CacheItemPolicy对象,它实现着对Cache对象超期的控制。例如前面的例子中,我们设置超时策略的方式是:AbsoluteExpiration = DateTime.Now.AddSeconds(3)。它表示的是一个绝对时间过期,当超过3秒钟后,Cache内容就会过期。
除此之外,我们还有一种比较常见的超期策略:按访问频度决定超期。例如,如果我们设置如下超期策略:SlidingExpiration = TimeSpan.FromSeconds(3)。它表示当对象3秒钟内没有得到访问时,就会过期。相对的,如果对象一直被访问,则不会过期。这两个策略并不能同时使用。
CacheItemPolicy也可以制定UpdateCallback和RemovedCallback,方便我们记日志或执行一些处理操作,非常方便。
ChangeMonitor
虽然前面列举的过期策略是非常常用的策略,能满足我们大多数时候的需求。但是有的时候,过期策略并不能简单的按照时间来判断。例如,我Cache的内容是从一个文本文件中读取的,此时过期的条件则是文件内容是否发生变化:当文件没有发生变更时,直接返回Cache内容,当问及发生变更时,Cache内容超期,需要重新读取文件。这个时候就需要用到ChangeMonitor来实现更为高级的超期判断了。
由于系统已经提供了文件变化的ChangeMonitor——HostFileChangeMonitor,这里就不用自己实现了,直接使用即可。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.Caching; using System.Threading; using System.IO; namespace CacheTest { class Program { static void Main(string[] args) { MyCachePool.Test(); Console.ReadKey(); } } class MyCachePool { ObjectCache cache = MemoryCache.Default; const string CacheKey = "TestCacheKey"; public string GetValueFromFile() { var content = cache[CacheKey] as string; var aaa = cache["persons"]; if (string.IsNullOrEmpty(content)) { Console.WriteLine("Get New Item"); var file = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "新建文本文档.txt"; // 指定缓存项的一组逐出和过期详细信息。 CacheItemPolicy policy = new CacheItemPolicy(); // 监视目录和文件路径,并向缓存通知被监视项的更改情况 policy.ChangeMonitors.Add(new HostFileChangeMonitor(new List<string> { file })); content = File.ReadAllText(file, Encoding.Default); cache.Set(CacheKey, content, policy); } else { Console.WriteLine("Get cached item"); } return content; } public static void Test() { var cachePool = new MyCachePool(); while (true) { Thread.Sleep(1000); var value = cachePool.GetValueFromFile(); Console.WriteLine(value); Console.WriteLine(); } } } }
当我们修改文件的时候,HostFileChangeMonitor会监控到,然后通知缓存,然后缓存会重新获取。

除了string类型,ObjectCache还是保存任何类型的数据,例如集合
public class MyCachePool { ObjectCache cache = MemoryCache.Default; readonly string CacheKey = "TestCacheKey"; /// <summary> /// 初始化两个缓存 /// </summary> public MyCachePool() { List<Person> persons = new List<Person>() { new Person {Name="n1",Age=15 }, new Person {Name="n2",Age=25 } }; var policy = new CacheItemPolicy() { AbsoluteExpiration = DateTime.Now.Add(TimeSpan.FromSeconds(10)) }; cache.Add(CacheKey, "111", policy); cache.Add("persons", persons, policy); } }

浙公网安备 33010602011771号