參考資料: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) }); } } } }