t;/returns>
public static T GetCacheItem<T>(string key, Func<T> cachePopulate, TimeSpan expiration,
string region = "_", ExpirationMode mode = ExpirationMode.Sliding) where T :class
{
CacheItem<object> outItem = null;
//通过AutoFac工厂获取对应的接口实现
var cache = AutoFactory.Instatnce.Container.Resolve<ICacheManager>();
if (cache != null)
{
if (cache.Manager.Get(key, region) == null)
{
lock (locker)
{
if (cache.Manager.Get(key, region) == null)
{
//Add、Put差异,Add只有在空值的情况下执行加入并返回true,Put总会替换并返回True
//如果按下面的方式加入,那么会留下历史丢弃的键值: cache.Manager.Put(key, value);
var value = cachePopulate();
var item = new CacheItem<object>(key, region, value, mode, expiration);
cache.Manager.Put(item);
}
}
}
return cache.Manager.Get(key, region) as T;
}
else
{
throw new ArgumentNullException("AutoFac配置参数错误,请检查autofac.config是否存在ICacheManager的定义");
}
}
}
不过由于官方已经提供了一个类似上面的代码逻辑的TryGetOrAdd方法,这个方法的定义如下所示。
TryGetOrAdd(String, String, Func<String, String, TCacheva lue>, out TCacheva lue)
Tries to either retrieve an existing item or add the item to the cache if it does not exist. The valueFactory will be eva luated only if the item does not exist.
Declaration
bool TryGetOrAdd(string key, string region, Func<string, string, TCacheva lue> valueFactory, out TCacheva lue value)
Parameters
Type |
Name |
Description |
String |
key |
The cache key. |
String |
region |
The cache region. |
Func<String, String, TCacheva lue> |
valueFactory |
The method which creates the value which should be added. |
TCacheva lue |
value |
The cache value. |
Returns
Type |
Description |
Boolean |
True if the operation succeeds, False in case there are too many retries or the valueFactory returns null. |
我们根据这个参数的定义,可以进一步简化上面的辅助类代码。
cache.Manager.TryGetOrAdd(key, region, (_key, _region) =>{
var value = cachePopulate();
var item = new CacheItem<object>(key, region, value, mode, expiration);
return item;
}, out outItem);
return outItem as T;
整个类的代码如下所示
/// <summary>
/// 基于.NET CacheManager的缓存管理,文档参考:http://cachemanager.michaco.net/documentation
/// </summary>
public class CacheManagerHelper
{
/// <summary>
/// 创建一个缓存的键值,并指定响应的时间范围,如果失效,则自动获取对应的值
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="key">对象的键</param>
/// <param name="cachePopulate">获取缓存值的操作</param>
/// <param name="expiration">失效的时间范围</param>
/// <param name="mode">失效类型</param>
/// <returns></returns>
public static T GetCacheItem<T>(string key, Func<T> cachePopulate, TimeSpan expiration,
string region = "_", ExpirationMode mode = ExpirationMode.Sliding) where T :class
{
CacheItem<object> outItem = null;
//通过AutoFac工厂获取对应的接口实现
var cache = AutoFactory.Instatnce.Container.Resolve<ICacheManager>();
if (cache != null)
{
cache.Manager.TryGetOrAdd(key, region, (_key, _region) =>{
var value = cachePopulate();
var item = new CacheItem<object>(key, region, value, mode, expiration);
retur |