NET 4.0中新增了一个System.Runtime.Caching的名字空间,它提供了一系列可扩展的Cache框架,本文就简单的介绍一下如何使用它给程序添加Cache。框架
一个Cache框架主要包括三个部分:ObjectCache、CacheItemPolicy、ChangeMonitor。ui
以下是一个简单的示例:spa
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");
var policy = new CacheItemPolicy() { AbsoluteExpiration = DateTime.Now.AddSeconds(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,获取到新的值。接口
过时策略:string
从前面的例子中咱们能够看到,将一个Cache对象加入CachePool中的时候,同时加入了一个CacheItemPolicy对象,它实现着对Cache对象超期的控制。例如前面的例子中,咱们设置超时策略的方式是:AbsoluteExpiration = DateTime.Now.AddSeconds(3)。它表示的是一个绝对时间过时,当超过3秒钟后,Cache内容就会过时。it
除此以外,咱们还有一种比较常见的超期策略:按访问频度决定超期。例如,若是咱们设置以下超期策略:SlidingExpiration = TimeSpan.FromSeconds(3)。它表示当对象3秒钟内没有获得访问时,就会过时。相对的,若是对象一直被访问,则不会过时。这两个策略并不能同时使用。io
CacheItemPolicy也能够制定UpdateCallback和RemovedCallback,方便咱们记日志或执行一些处理操做,很是方便。class
ChangeMonitor
虽然前面列举的过时策略是很是经常使用的策略,能知足咱们大多数时候的需求。可是有的时候,过时策略并不能简单的按照时间来判断。例如,我Cache的内容是从一个文本文件中读取的,此时过时的条件则是文件内容是否发生变化:当文件没有发生变动时,直接返回Cache内容,当问及发生变动时,Cache内容超期,须要从新读取文件。这个时候就须要用到ChangeMonitor来实现更为高级的超期判断了。
因为系统已经提供了文件变化的ChangeMonitor——HostFileChangeMonitor,这里就不用本身实现了,直接使用便可。
public string GetValue()
{
var content = cache[CacheKey] as string;
if(content == null)
{
Console.WriteLine("Get New Item");
var file = @"r:\test.txt";
CacheItemPolicy policy = new CacheItemPolicy();
policy.ChangeMonitors.Add(new HostFileChangeMonitor(new List<string> { file }));
content = File.ReadAllText(file);
cache.Set(CacheKey, content, policy);
}
else
{
Console.WriteLine("Get cached item");
}
return content;
}
这个例子仍是比较简单的,对于那些没有自定义的策略,则须要咱们实现本身的ChangeMonitor,如今一时也想不到合适的例子,下次有时间在写篇文章更深刻的介绍一下吧。