SysCacheService.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. // Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
  2. //
  3. // 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
  4. //
  5. // 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
  6. using NewLife.Caching.Models;
  7. namespace Admin.NET.Core.Service;
  8. /// <summary>
  9. /// 系统缓存服务 🧩
  10. /// </summary>
  11. [ApiDescriptionSettings(Order = 400)]
  12. public class SysCacheService : IDynamicApiController, ISingleton
  13. {
  14. private static ICacheProvider _cacheProvider;
  15. private readonly CacheOptions _cacheOptions;
  16. public SysCacheService(ICacheProvider cacheProvider, IOptions<CacheOptions> cacheOptions)
  17. {
  18. _cacheProvider = cacheProvider;
  19. _cacheOptions = cacheOptions.Value;
  20. }
  21. /// <summary>
  22. /// 获取缓存键名集合 🔖
  23. /// </summary>
  24. /// <returns></returns>
  25. [DisplayName("获取缓存键名集合")]
  26. public List<string> GetKeyList()
  27. {
  28. return _cacheProvider.Cache == Cache.Default
  29. ? _cacheProvider.Cache.Keys.Where(u => u.StartsWith(_cacheOptions.Prefix)).Select(u => u[_cacheOptions.Prefix.Length..]).OrderBy(u => u).ToList()
  30. : ((FullRedis)_cacheProvider.Cache).Search($"{_cacheOptions.Prefix}*", int.MaxValue).Select(u => u[_cacheOptions.Prefix.Length..]).OrderBy(u => u).ToList();
  31. }
  32. /// <summary>
  33. /// 增加缓存
  34. /// </summary>
  35. /// <param name="key"></param>
  36. /// <param name="value"></param>
  37. /// <returns></returns>
  38. [NonAction]
  39. public bool Set(string key, object value)
  40. {
  41. if (string.IsNullOrWhiteSpace(key)) return false;
  42. return _cacheProvider.Cache.Set($"{_cacheOptions.Prefix}{key}", value);
  43. }
  44. /// <summary>
  45. /// 增加缓存并设置过期时间
  46. /// </summary>
  47. /// <param name="key"></param>
  48. /// <param name="value"></param>
  49. /// <param name="expire"></param>
  50. /// <returns></returns>
  51. [NonAction]
  52. public bool Set(string key, object value, TimeSpan expire)
  53. {
  54. if (string.IsNullOrWhiteSpace(key)) return false;
  55. return _cacheProvider.Cache.Set($"{_cacheOptions.Prefix}{key}", value, expire);
  56. }
  57. /// <summary>
  58. /// 获取缓存
  59. /// </summary>
  60. /// <typeparam name="T"></typeparam>
  61. /// <param name="key"></param>
  62. /// <returns></returns>
  63. [NonAction]
  64. public T Get<T>(string key)
  65. {
  66. return _cacheProvider.Cache.Get<T>($"{_cacheOptions.Prefix}{key}");
  67. }
  68. /// <summary>
  69. /// 删除缓存 🔖
  70. /// </summary>
  71. /// <param name="key"></param>
  72. /// <returns></returns>
  73. [ApiDescriptionSettings(Name = "Delete"), HttpPost]
  74. [DisplayName("删除缓存")]
  75. public int Remove(string key)
  76. {
  77. return _cacheProvider.Cache.Remove($"{_cacheOptions.Prefix}{key}");
  78. }
  79. /// <summary>
  80. /// 清空所有缓存 🔖
  81. /// </summary>
  82. /// <returns></returns>
  83. [DisplayName("清空所有缓存")]
  84. [ApiDescriptionSettings(Name = "Clear"), HttpPost]
  85. public void Clear()
  86. {
  87. _cacheProvider.Cache.Clear();
  88. Cache.Default.Clear();
  89. }
  90. /// <summary>
  91. /// 检查缓存是否存在
  92. /// </summary>
  93. /// <param name="key">键</param>
  94. /// <returns></returns>
  95. [NonAction]
  96. public bool ExistKey(string key)
  97. {
  98. return _cacheProvider.Cache.ContainsKey($"{_cacheOptions.Prefix}{key}");
  99. }
  100. /// <summary>
  101. /// 根据键名前缀删除缓存 🔖
  102. /// </summary>
  103. /// <param name="prefixKey">键名前缀</param>
  104. /// <returns></returns>
  105. [ApiDescriptionSettings(Name = "DeleteByPreKey"), HttpPost]
  106. [DisplayName("根据键名前缀删除缓存")]
  107. public int RemoveByPrefixKey(string prefixKey)
  108. {
  109. var delKeys = _cacheProvider.Cache == Cache.Default
  110. ? _cacheProvider.Cache.Keys.Where(u => u.StartsWith($"{_cacheOptions.Prefix}{prefixKey}")).ToArray()
  111. : ((FullRedis)_cacheProvider.Cache).Search($"{_cacheOptions.Prefix}{prefixKey}*", int.MaxValue).ToArray();
  112. return _cacheProvider.Cache.Remove(delKeys);
  113. }
  114. /// <summary>
  115. /// 根据键名前缀获取键名集合 🔖
  116. /// </summary>
  117. /// <param name="prefixKey">键名前缀</param>
  118. /// <returns></returns>
  119. [DisplayName("根据键名前缀获取键名集合")]
  120. public List<string> GetKeysByPrefixKey(string prefixKey)
  121. {
  122. return _cacheProvider.Cache == Cache.Default
  123. ? _cacheProvider.Cache.Keys.Where(u => u.StartsWith($"{_cacheOptions.Prefix}{prefixKey}")).Select(u => u[_cacheOptions.Prefix.Length..]).ToList()
  124. : ((FullRedis)_cacheProvider.Cache).Search($"{_cacheOptions.Prefix}{prefixKey}*", int.MaxValue).Select(u => u[_cacheOptions.Prefix.Length..]).ToList();
  125. }
  126. /// <summary>
  127. /// 获取缓存值 🔖
  128. /// </summary>
  129. /// <param name="key"></param>
  130. /// <returns></returns>
  131. [DisplayName("获取缓存值")]
  132. public object GetValue(string key)
  133. {
  134. // 若Key经过URL编码则进行解码
  135. if (Regex.IsMatch(key, @"%[0-9a-fA-F]{2}"))
  136. key = HttpUtility.UrlDecode(key);
  137. return _cacheProvider.Cache == Cache.Default
  138. ? _cacheProvider.Cache.Get<object>($"{_cacheOptions.Prefix}{key}")
  139. : _cacheProvider.Cache.Get<string>($"{_cacheOptions.Prefix}{key}");
  140. }
  141. /// <summary>
  142. /// 获取或添加缓存(在数据不存在时执行委托请求数据)
  143. /// </summary>
  144. /// <typeparam name="T"></typeparam>
  145. /// <param name="key"></param>
  146. /// <param name="callback"></param>
  147. /// <param name="expire">过期时间,单位秒</param>
  148. /// <returns></returns>
  149. [NonAction]
  150. public T GetOrAdd<T>(string key, Func<string, T> callback, int expire = -1)
  151. {
  152. if (string.IsNullOrWhiteSpace(key)) return default;
  153. return _cacheProvider.Cache.GetOrAdd($"{_cacheOptions.Prefix}{key}", callback, expire);
  154. }
  155. /// <summary>
  156. /// Hash匹配
  157. /// </summary>
  158. /// <typeparam name="T"></typeparam>
  159. /// <param name="key"></param>
  160. /// <returns></returns>
  161. [NonAction]
  162. public RedisHash<string, T> GetHashMap<T>(string key)
  163. {
  164. return _cacheProvider.Cache.GetDictionary<T>(key) as RedisHash<string, T>;
  165. }
  166. /// <summary>
  167. /// 批量添加HASH
  168. /// </summary>
  169. /// <typeparam name="T"></typeparam>
  170. /// <param name="key"></param>
  171. /// <param name="dic"></param>
  172. /// <returns></returns>
  173. [NonAction]
  174. public bool HashSet<T>(string key, Dictionary<string, T> dic)
  175. {
  176. var hash = GetHashMap<T>(key);
  177. return hash.HMSet(dic);
  178. }
  179. /// <summary>
  180. /// 添加一条HASH
  181. /// </summary>
  182. /// <typeparam name="T"></typeparam>
  183. /// <param name="key"></param>
  184. /// <param name="hashKey"></param>
  185. /// <param name="value"></param>
  186. [NonAction]
  187. public void HashAdd<T>(string key, string hashKey, T value)
  188. {
  189. var hash = GetHashMap<T>(key);
  190. hash.Add(hashKey, value);
  191. }
  192. /// <summary>
  193. /// 获取多条HASH
  194. /// </summary>
  195. /// <typeparam name="T"></typeparam>
  196. /// <param name="key"></param>
  197. /// <param name="fields"></param>
  198. /// <returns></returns>
  199. [NonAction]
  200. public List<T> HashGet<T>(string key, params string[] fields)
  201. {
  202. var hash = GetHashMap<T>(key);
  203. var result = hash.HMGet(fields);
  204. return result.ToList();
  205. }
  206. /// <summary>
  207. /// 获取一条HASH
  208. /// </summary>
  209. /// <typeparam name="T"></typeparam>
  210. /// <param name="key"></param>
  211. /// <param name="field"></param>
  212. /// <returns></returns>
  213. [NonAction]
  214. public T HashGetOne<T>(string key, string field)
  215. {
  216. var hash = GetHashMap<T>(key);
  217. var result = hash.HMGet(new string[] { field });
  218. return result[0];
  219. }
  220. /// <summary>
  221. /// 根据KEY获取所有HASH
  222. /// </summary>
  223. /// <typeparam name="T"></typeparam>
  224. /// <param name="key"></param>
  225. /// <returns></returns>
  226. [NonAction]
  227. public IDictionary<string, T> HashGetAll<T>(string key)
  228. {
  229. var hash = GetHashMap<T>(key);
  230. return hash.GetAll();
  231. }
  232. /// <summary>
  233. /// 删除HASH
  234. /// </summary>
  235. /// <typeparam name="T"></typeparam>
  236. /// <param name="key"></param>
  237. /// <param name="fields"></param>
  238. /// <returns></returns>
  239. [NonAction]
  240. public int HashDel<T>(string key, params string[] fields)
  241. {
  242. var hash = GetHashMap<T>(key);
  243. return hash.HDel(fields);
  244. }
  245. /// <summary>
  246. /// 搜索HASH
  247. /// </summary>
  248. /// <typeparam name="T"></typeparam>
  249. /// <param name="key"></param>
  250. /// <param name="searchModel"></param>
  251. /// <returns></returns>
  252. [NonAction]
  253. public List<KeyValuePair<string, T>> HashSearch<T>(string key, SearchModel searchModel)
  254. {
  255. var hash = GetHashMap<T>(key);
  256. return hash.Search(searchModel).ToList();
  257. }
  258. /// <summary>
  259. /// 搜索HASH
  260. /// </summary>
  261. /// <typeparam name="T"></typeparam>
  262. /// <param name="key"></param>
  263. /// <param name="pattern"></param>
  264. /// <param name="count"></param>
  265. /// <returns></returns>
  266. [NonAction]
  267. public List<KeyValuePair<string, T>> HashSearch<T>(string key, string pattern, int count)
  268. {
  269. var hash = GetHashMap<T>(key);
  270. return hash.Search(pattern, count).ToList();
  271. }
  272. }