注意需引用System.Runtime.Caching.dll
public static class CacheManagerHelper
{
private static object _lockObj = new object();
private readonly static MemoryCache _cache;
static CacheManager()
{
_cache = MemoryCache.Default;
}
public static void Remove(string key)
{
_cache.Remove(key);
}
public static T Get<T>(string key)
{
return (T)_cache.Get(key);
}
public static void Set(CacheItem cacheItem, CacheItemPolicy policy)
{
_cache.AddOrGetExisting(cacheItem, policy);
}
public static void Set<T>(string key, T item, int minutes = 5)
{
if (item == null)
return;
_cache.AddOrGetExisting(key, item, DateTime.Now.Add(TimeSpan.FromMinutes(minutes)));
}
public static T Get<T>(Func<KeyValuePair<string, object>, bool> predicate)
{
return (T)_cache.FirstOrDefault(predicate).Value;
}
public static bool Contains(string key)
{
return _cache.Contains(key);
}
}