参考资料:long0801的博客、MemoryCache微软官方文档
添加对Microsoft.Extensions.Caching.Memory命名空间的引用,它提供了.NET Core默认实现的MemoryCache类,以及全新的内存缓存API
代码如下:
using System; using Microsoft.Extensions.Caching.Memory; namespace FrameWork.Common.DotNetCache { public class CacheHelper { static readonly MemoryCache Cache = new MemoryCache(new MemoryCacheOptions()); /// <summary> /// 获取缓存中的值 /// </summary> /// <param name="key">键</param> /// <returns>值</returns> public static object GetCacheValue(string key) { if ( !string.IsNullOrEmpty(key) && Cache.TryGetValue(key, out var val)) { return val; } return default(object); } /// <summary> /// 设置缓存 /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> public static void SetCacheValue(string key, object value) { if (!string.IsNullOrEmpty(key)) { Cache.Set(key, value, new MemoryCacheEntryOptions { SlidingExpiration = TimeSpan.FromHours(1) }); } } } }