[更新]缓存管理的帮助类(MemoryCache版,需要.net 4以上)
本来想发布下新版Luke.Net,正好刚刚再次重构了缓存的帮助类这里发布下:
测试代码
[Fact] public void SimpleTest() { ICache<int, string> cacheMenager = MemoryCache<int, string>.Instance; var value = cacheMenager.Get(1, () => 1, TimeSpan.FromSeconds(10)); Assert.Equal(value, 1); value = cacheMenager.Get(1, () => 2, TimeSpan.FromSeconds(10)); Assert.Equal(value, 1); System.Threading.Thread.Sleep(10 * 1000); value = cacheMenager.Get(1, () => 3, TimeSpan.FromSeconds(10)); Assert.Equal(value, 3); }
接口
public interface ICache<TK,TV> { TV Get<TV>(TK cacheKey, Func<TV> getUncachedValue, DateTimeOffset dateTimeOffset); TV Get<TV>(TK cacheKey, Func<TV> getUncachedValue, TimeSpan timeSpan); void Remove(TK cacheKey); }
用到的单例类
public class SingletonProvider<T> where T : new() { SingletonProvider() { } public static T Instance { get { return SingletonCreator.instance; } } class SingletonCreator { static SingletonCreator() { } internal static readonly T instance = new T(); } }
最后是更新后的缓存类,
public class MemoryCache<TK, TV> : ICache<TK, TV> { private ObjectCache _memoryCache; public static MemoryCache<TK, TV> Instance { get { return SingletonProvider<MemoryCache<TK, TV>>.Instance; } } public MemoryCache() : this(null) { } public MemoryCache(string name) { _memoryCache = new MemoryCache(string.Format("{0}-{1}-{2}", typeof(TK).Name, typeof(TV).Name, name)); } public TV Get<TV>(TK cacheKey, Func<TV> getUncachedValue, DateTimeOffset dateTimeOffset) { if (_memoryCache.Contains(ParseKey(cacheKey))) { return (TV)_memoryCache[ParseKey(cacheKey)]; } else { var v = getUncachedValue(); object o = v; _memoryCache.Set(ParseKey(cacheKey), o, dateTimeOffset); return v; } } public TV Get<TV>(TK cacheKey, Func<TV> getUncachedValue, TimeSpan timeSpan) { return Get(cacheKey, getUncachedValue, new DateTimeOffset(DateTime.UtcNow + timeSpan)); } public void Remove(TK cacheKey) { _memoryCache.Remove(ParseKey(cacheKey)); } private string ParseKey(TK key) { return key.GetHashCode().ToString(); } }