对于传统的.NET Framework项目而言,System.Runtime.Caching命名空间是经常使用的工具了,其中MemoryCache类则常被用于实现内存缓存。缓存
.NET Core 2.0暂时还不支持System.Runtime.Caching dll,这也就意味着MemoryCache相关代码再也不起做用了。工具
using System; using System.Runtime.Caching; namespace TestWebApp.Service { public class MemoryCacheService { static ObjectCache cache = MemoryCache.Default; /// <summary> /// 获取缓存值 /// </summary> /// <param name="key"></param> /// <returns></returns> private object GetCacheValue(string key) { if (key != null && cache.Contains(key)) { return cache[key]; } return default(object); } /// <summary> /// 添加缓存内容 /// </summary> /// <param name="key"></param> /// <param name="value"></param> public static void SetChacheValue(string key, object value) { if (key != null) { CacheItemPolicy policy = new CacheItemPolicy { SlidingExpiration = TimeSpan.FromHours(1) }; cache.Set(key, value, policy); } } } }
导入后你会发现VS会提示没法找到System.Runtime.Caching命名空间,原有的代码没法直接编译使用。spa
using Microsoft.Extensions.Caching.Memory;
初始化缓存对象方式改写前:code
static ObjectCache cache = MemoryCache.Default;
初始化缓存对象方式改写后:对象
static MemoryCache cache = new MemoryCache(new MemoryCacheOptions());
读取内存缓存值方式变化:blog
private object GetCacheValue(string key) { if (key != null && cache.Contains(key)) { return cache[key]; } return default(object); }
改写后:内存
private object GetCacheValue(string key) { object val = null; if (key != null && cache.TryGetValue(key, out val)) { return val; } else { return default(object); } }
设定内存缓存内容方式变化:string
public static void SetChacheValue(string key, object value) { if (key != null) { CacheItemPolicy policy = new CacheItemPolicy { SlidingExpiration = TimeSpan.FromHours(1) }; cache.Set(key, value, policy); } }
修改后:io
public static void SetChacheValue(string key, object value) { if (key != null) { cache.Set(key, value, new MemoryCacheEntryOptions { SlidingExpiration = TimeSpan.FromHours(1) }); } }
在使用了Microsoft.Extensions.Caching.Memory下的新API改写了旧代码后,你会发现原有的各类内存缓存超时策略全都是有对应新API的,包括AbsoluteExpiration, SlidingExpiration等等。编译
因此咱们仍是能够很轻松的使用.NET Core新API简单改动下下就能重用现有绝大部分旧代码,将其迁移过来继续起做用。
迁移后的完整代码以下:
using Microsoft.Extensions.Caching.Memory; using System; namespace TestMemoryCacheWebApp.Services { public class MemoryCacheService { static MemoryCache cache = new MemoryCache(new MemoryCacheOptions()); /// <summary> /// 获取缓存值 /// </summary> /// <param name="key"></param> /// <returns></returns> private object GetCacheValue(string key) { object val = null; if (key != null && cache.TryGetValue(key, out val)) { return val; } else { return default(object); } } /// <summary> /// 添加缓存内容 /// </summary> /// <param name="key"></param> /// <param name="value"></param> public static void SetChacheValue(string key, object value) { if (key != null) { cache.Set(key, value, new MemoryCacheEntryOptions { SlidingExpiration = TimeSpan.FromHours(1) }); } } } }