Netcore中简单使用MemoryCache
用到缓存架构,我们一般都会想到的Redis,因为它支持分布式,高可用,速率非常快。MemoryCache则相对较少提到,但是对于单体项目或者小型项目,memorycache还是是不错的选择。MemoryCache是netcore中集成的缓存架构,使用起来非常的简单方便。
meorycache简单的代码封装
1 /// <summary>
2 /// memorycache管理类
3 /// </summary>
4 public class MemoryCacheManagement
5 {
6 public static MemoryCacheManagement Default = new MemoryCacheManagement();
7
8 private IMemoryCache _cache = new MemoryCache(new MemoryCacheOptions());
9 private MemoryCacheManagement()
10 {
11
12 }
13
14 /// <summary>
15 /// 设置缓存,不设置超时时间
16 /// </summary>
17 /// <typeparam name="T"></typeparam>
18 /// <param name="key"></param>
19 /// <param name="value"></param>
20 public void SetValue<T>(string key, T value)
21 {
22 if (string.IsNullOrEmpty(key))
23 {
24 throw new ArgumentNullException("key");
25 }
26 T t;
27 if (_cache.TryGetValue<T>(key, out t))
28 {
29 _cache.Remove(key);
30 }
31 _cache.Set(key, value);
32 }
33 /// <summary>
34 /// 设置缓存,并指定绝对超时时间
35 /// </summary>
36 /// <typeparam name="T"></typeparam>
37 /// <param name="key"></param>
38 /// <param name="value"></param>
39 /// <param name="absoluteTimeoutSeconds"></param>
40 public void SetValue<T>(string key, T value, int absoluteTimeoutSeconds)
41 {
42 if (string.IsNullOrEmpty(key))
43 {
44 throw new ArgumentNullException("key");
45 }
46 T t;
47 if (_cache.TryGetValue<T>(key, out t))
48 {
49 _cache.Remove(key);
50 }
51 _cache.Set<T>(key, value, DateTimeOffset.Now.AddSeconds(absoluteTimeoutSeconds));
52 }
53 /// <summary>
54 /// 设置缓存,并设定超时时间,不访问(滑动)超时时间
55 /// </summary>
56 /// <typeparam name="T"></typeparam>
57 /// <param name="key"></param>
58 /// <param name="value"></param>
59 /// <param name="absoluteTimeoutSeconds"></param>
60 /// <param name="slidingExpirationSeconds"></param>
61 public void SetValue<T>(string key, T value, int absoluteTimeoutSeconds, int slidingExpirationSeconds)
62 {
63 if (string.IsNullOrEmpty(key))
64 {
65 throw new ArgumentNullException("key");
66 }
67 T t;
68 if (_cache.TryGetValue<T>(key, out t))
69 {
70 _cache.Remove(key);
71 }
72 _cache.Set(key, value, new MemoryCacheEntryOptions()
73 {
74 AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(absoluteTimeoutSeconds), //绝对超时时间,
75 SlidingExpiration = TimeSpan.FromSeconds(slidingExpirationSeconds), //不访问超时时间(在这个指定的时段内没有使用则过期,否则顺延)
76 });
77 }
78 /// <summary>
79 /// 获取缓存值
80 /// </summary>
81 /// <typeparam name="T"></typeparam>
82 /// <param name="key"></param>
83 /// <returns></returns>