MemoryCache.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. using Microsoft.Extensions.Caching.Memory;
  2. using System.Collections;
  3. using System.Reflection;
  4. using System.Text.RegularExpressions;
  5. namespace EasyTemplate.Tool;
  6. /// <summary>
  7. /// 缓存帮助类
  8. /// </summary>
  9. public class MemoryCache
  10. {
  11. private static readonly Microsoft.Extensions.Caching.Memory.MemoryCache Cache = new Microsoft.Extensions.Caching.Memory.MemoryCache(new MemoryCacheOptions());
  12. /// <summary>
  13. /// 验证缓存项是否存在
  14. /// </summary>
  15. /// <param name="key">缓存Key</param>
  16. /// <returns></returns>
  17. public static bool Exists(string key)
  18. {
  19. if (key == null)
  20. throw new ArgumentNullException(nameof(key));
  21. return Cache.TryGetValue(key, out _);
  22. }
  23. /// <summary>
  24. /// 添加缓存
  25. /// </summary>
  26. /// <param name="key">缓存Key</param>
  27. /// <param name="value">缓存Value</param>
  28. /// <param name="expiresSliding">滑动过期时长(如果在过期时间内有操作,则以当前时间点延长过期时间)</param>
  29. /// <param name="expiressAbsoulte">绝对过期时长</param>
  30. /// <returns></returns>
  31. public static bool Set(string key, object value, TimeSpan expiresSliding, TimeSpan expiressAbsoulte)
  32. {
  33. if (key == null)
  34. throw new ArgumentNullException(nameof(key));
  35. if (value == null)
  36. throw new ArgumentNullException(nameof(value));
  37. Cache.Set(key, value.ToJson(),
  38. new MemoryCacheEntryOptions().SetSlidingExpiration(expiresSliding)
  39. .SetAbsoluteExpiration(expiressAbsoulte));
  40. return Exists(key);
  41. }
  42. /// <summary>
  43. /// 添加缓存
  44. /// </summary>
  45. /// <param name="key">缓存Key</param>
  46. /// <param name="value">缓存Value</param>
  47. /// <param name="expiresIn">缓存时长</param>
  48. /// <param name="isSliding">是否滑动过期(如果在过期时间内有操作,则以当前时间点延长过期时间)</param>
  49. /// <returns></returns>
  50. public static bool Set(string key, object value, TimeSpan expiresIn, bool isSliding = false)
  51. {
  52. if (key == null)
  53. throw new ArgumentNullException(nameof(key));
  54. if (value == null)
  55. throw new ArgumentNullException(nameof(value));
  56. Cache.Set(key, value.ToJson(),
  57. isSliding
  58. ? new MemoryCacheEntryOptions().SetSlidingExpiration(expiresIn)
  59. : new MemoryCacheEntryOptions().SetAbsoluteExpiration(expiresIn));
  60. return Exists(key);
  61. }
  62. /// <summary>
  63. /// 添加缓存
  64. /// </summary>
  65. /// <param name="key">缓存Key</param>
  66. /// <param name="value">缓存Value</param>
  67. /// <returns></returns>
  68. public static bool Set(string key, object value)
  69. {
  70. if (key == null)
  71. throw new ArgumentNullException(nameof(key));
  72. if (value == null)
  73. throw new ArgumentNullException(nameof(value));
  74. Cache.Set(key, value.ToJson());
  75. return Exists(key);
  76. }
  77. #region 删除缓存
  78. /// <summary>
  79. /// 删除缓存
  80. /// </summary>
  81. /// <param name="key">缓存Key</param>
  82. /// <returns></returns>
  83. public static void Remove(string key)
  84. {
  85. if (key == null)
  86. throw new ArgumentNullException(nameof(key));
  87. Cache.Remove(key);
  88. }
  89. /// <summary>
  90. /// 批量删除缓存
  91. /// </summary>
  92. /// <returns></returns>
  93. public static void RemoveAll(IEnumerable<string> keys)
  94. {
  95. if (keys == null)
  96. throw new ArgumentNullException(nameof(keys));
  97. keys.ToList().ForEach(item => Cache.Remove(item));
  98. }
  99. #endregion 删除缓存
  100. #region 获取缓存
  101. /// <summary>
  102. /// 获取缓存
  103. /// </summary>
  104. /// <param name="key">缓存Key</param>
  105. /// <returns></returns>
  106. public static T Get<T>(string key)
  107. {
  108. if (key == null)
  109. throw new ArgumentNullException(nameof(key));
  110. object temp;
  111. if (Cache.TryGetValue(key, out temp))
  112. {
  113. return temp.ToString().ToEntity<T>();
  114. }
  115. return default(T);
  116. }
  117. /// <summary>
  118. /// 获取缓存
  119. /// </summary>
  120. /// <param name="key">缓存Key</param>
  121. /// <returns></returns>
  122. public static string Get(string key)
  123. {
  124. if (key == null)
  125. throw new ArgumentNullException(nameof(key));
  126. if (Cache.Get(key) == null)
  127. {
  128. return string.Empty;
  129. }
  130. return Cache.Get(key).ToString();
  131. }
  132. /// <summary>
  133. /// 获取缓存
  134. /// </summary>
  135. /// <param name="key">缓存Key</param>
  136. /// <returns></returns>
  137. public static T GetT<T>(string key)
  138. {
  139. if (key == null)
  140. throw new ArgumentNullException(nameof(key));
  141. var temp = Cache.Get(key);
  142. if (temp == null)
  143. {
  144. return default;
  145. }
  146. return Cache.Get(key).ToString().ToEntity<T>();
  147. }
  148. /// <summary>
  149. /// 获取缓存集合
  150. /// </summary>
  151. /// <param name="keys">缓存Key集合</param>
  152. /// <returns></returns>
  153. public static IDictionary<string, object> GetAll(IEnumerable<string> keys)
  154. {
  155. if (keys == null)
  156. throw new ArgumentNullException(nameof(keys));
  157. var dict = new Dictionary<string, object>();
  158. keys.ToList().ForEach(item => dict.Add(item, Cache.Get(item)));
  159. return dict;
  160. }
  161. #endregion 获取缓存
  162. /// <summary>
  163. /// 删除所有缓存
  164. /// </summary>
  165. public static void RemoveCacheAll()
  166. {
  167. var l = GetCacheKeys();
  168. foreach (var s in l)
  169. {
  170. Remove(s);
  171. }
  172. }
  173. /// <summary>
  174. /// 删除匹配到的缓存
  175. /// </summary>
  176. /// <param name="pattern"></param>
  177. /// <returns></returns>
  178. public static void RemoveCacheRegex(string pattern)
  179. {
  180. IEnumerable<string> l = SearchCacheRegex(pattern);
  181. foreach (var s in l)
  182. {
  183. Remove(s);
  184. }
  185. }
  186. /// <summary>
  187. /// 搜索 匹配到的缓存
  188. /// </summary>
  189. /// <param name="pattern"></param>
  190. /// <returns></returns>
  191. public static IEnumerable<string> SearchCacheRegex(string pattern)
  192. {
  193. var cacheKeys = GetCacheKeys();
  194. var l = cacheKeys.Where(k => Regex.IsMatch(k, pattern)).ToList();
  195. return l.AsReadOnly();
  196. }
  197. /// <summary>
  198. /// 获取所有缓存键
  199. /// </summary>
  200. /// <returns></returns>
  201. public static List<string> GetCacheKeys()
  202. {
  203. #if NET8_0
  204. const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
  205. var entries = Cache.GetType().GetField("_coherentState", flags)?.GetValue(Cache);
  206. var cacheItems = entries?.GetType()?.GetProperty("EntriesCollection", flags)?.GetValue(entries) as ICollection; //entries as IDictionary;
  207. var keys = new List<string>();
  208. if (cacheItems == null) return keys;
  209. foreach (var item in cacheItems)
  210. {
  211. var methodInfo = item.GetType().GetProperty("Key");
  212. var val = methodInfo.GetValue(item);
  213. keys.Add(val.ToString());
  214. }
  215. return keys;
  216. #else
  217. const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
  218. var entries = Cache.GetType().GetField("_entries", flags).GetValue(Cache);
  219. var cacheItems = entries as IDictionary;
  220. var keys = new List<string>();
  221. if (cacheItems == null) return keys;
  222. foreach (DictionaryEntry cacheItem in cacheItems)
  223. {
  224. keys.Add(cacheItem.Key.ToString());
  225. }
  226. return keys;
  227. #endif
  228. }
  229. }