.NET Core MemoryCache的使用

好像是没有 nuget 包的直接using即可。

using Microsoft.Extensions.Caching.Memory;
 1   public static class CacheHelperNetCore
 2     {
 3         public static IMemoryCache _memoryCache = new MemoryCache(new MemoryCacheOptions());
 4         /// <summary>
 5         /// 设置key值缓存
 6         /// </summary>
 7         /// <param name="key"></param>
 8         /// <param name="obj"></param>
 9         /// <param name="timeSpan">过期时间</param>
10         public static void SetCache(string key,object obj,TimeSpan timeSpan)
11         {
12             _memoryCache.Set(key,obj,timeSpan);
13         }
14         /// <summary>
15         /// 获取key值缓存
16         /// </summary>
17         /// <param name="key"></param>
18         /// <returns></returns>
19         public static object GetCache(string key)
20         {
21             return _memoryCache.Get(key);
22         }
23         /// <summary>
24         /// 获取key值缓存
25         /// </summary>
26         /// <typeparam name="T"></typeparam>
27         /// <param name="key"></param>
28         /// <returns></returns>
29         public static T GetCache<T>(string key)
30         {
31             return _memoryCache.Get<T>(key);
32         }
33         /// <summary>
34         /// 该key值缓存是否存在
35         /// </summary>
36         /// <param name="key"></param>
37         /// <returns></returns>
38         public static bool Exist(string key)
39         {
40             return _memoryCache.TryGetValue(key,out _);
41         }
42     }

基本都是常用的,提升下性能还是可以的。不过有持久化需求或者对数据结构和处理有高级要求的建议选择Redis。

原文地址:https://www.cnblogs.com/ya-jun/p/13213792.html