SysCacheService.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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. /// <param name="key">键</param>
  83. /// <returns></returns>
  84. [NonAction]
  85. public bool ExistKey(string key)
  86. {
  87. return _cacheProvider.Cache.ContainsKey($"{_cacheOptions.Prefix}{key}");
  88. }
  89. /// <summary>
  90. /// 根据键名前缀删除缓存 🔖
  91. /// </summary>
  92. /// <param name="prefixKey">键名前缀</param>
  93. /// <returns></returns>
  94. [ApiDescriptionSettings(Name = "DeleteByPreKey"), HttpPost]
  95. [DisplayName("根据键名前缀删除缓存")]
  96. public int RemoveByPrefixKey(string prefixKey)
  97. {
  98. var delKeys = _cacheProvider.Cache == Cache.Default
  99. ? _cacheProvider.Cache.Keys.Where(u => u.StartsWith($"{_cacheOptions.Prefix}{prefixKey}")).ToArray()
  100. : ((FullRedis)_cacheProvider.Cache).Search($"{_cacheOptions.Prefix}{prefixKey}*", int.MaxValue).ToArray();
  101. return _cacheProvider.Cache.Remove(delKeys);
  102. }
  103. /// <summary>
  104. /// 根据键名前缀获取键名集合 🔖
  105. /// </summary>
  106. /// <param name="prefixKey">键名前缀</param>
  107. /// <returns></returns>
  108. [DisplayName("根据键名前缀获取键名集合")]
  109. public List<string> GetKeysByPrefixKey(string prefixKey)
  110. {
  111. return _cacheProvider.Cache == Cache.Default
  112. ? _cacheProvider.Cache.Keys.Where(u => u.StartsWith($"{_cacheOptions.Prefix}{prefixKey}")).Select(u => u[_cacheOptions.Prefix.Length..]).ToList()
  113. : ((FullRedis)_cacheProvider.Cache).Search($"{_cacheOptions.Prefix}{prefixKey}*", int.MaxValue).Select(u => u[_cacheOptions.Prefix.Length..]).ToList();
  114. }
  115. /// <summary>
  116. /// 获取缓存值 🔖
  117. /// </summary>
  118. /// <param name="key"></param>
  119. /// <returns></returns>
  120. [DisplayName("获取缓存值")]
  121. public object GetValue(string key)
  122. {
  123. // 若Key经过URL编码则进行解码
  124. if (Regex.IsMatch(key, @"%[0-9a-fA-F]{2}"))
  125. key = HttpUtility.UrlDecode(key);
  126. return _cacheProvider.Cache == Cache.Default
  127. ? _cacheProvider.Cache.Get<object>($"{_cacheOptions.Prefix}{key}")
  128. : _cacheProvider.Cache.Get<string>($"{_cacheOptions.Prefix}{key}");
  129. }
  130. /// <summary>
  131. /// 获取或添加缓存(在数据不存在时执行委托请求数据)
  132. /// </summary>
  133. /// <typeparam name="T"></typeparam>
  134. /// <param name="key"></param>
  135. /// <param name="callback"></param>
  136. /// <param name="expire">过期时间,单位秒</param>
  137. /// <returns></returns>
  138. [NonAction]
  139. public T GetOrAdd<T>(string key, Func<string, T> callback, int expire = -1)
  140. {
  141. if (string.IsNullOrWhiteSpace(key)) return default;
  142. return _cacheProvider.Cache.GetOrAdd($"{_cacheOptions.Prefix}{key}", callback, expire);
  143. }
  144. /// <summary>
  145. /// Hash匹配
  146. /// </summary>
  147. /// <typeparam name="T"></typeparam>
  148. /// <param name="key"></param>
  149. /// <returns></returns>
  150. [NonAction]
  151. public RedisHash<string, T> GetHashMap<T>(string key)
  152. {
  153. return _cacheProvider.Cache.GetDictionary<T>(key) as RedisHash<string, T>;
  154. }
  155. /// <summary>
  156. /// 批量添加HASH
  157. /// </summary>
  158. /// <typeparam name="T"></typeparam>
  159. /// <param name="key"></param>
  160. /// <param name="dic"></param>
  161. /// <returns></returns>
  162. [NonAction]
  163. public bool HashSet<T>(string key, Dictionary<string, T> dic)
  164. {
  165. var hash = GetHashMap<T>(key);
  166. return hash.HMSet(dic);
  167. }
  168. /// <summary>
  169. /// 添加一条HASH
  170. /// </summary>
  171. /// <typeparam name="T"></typeparam>
  172. /// <param name="key"></param>
  173. /// <param name="hashKey"></param>
  174. /// <param name="value"></param>
  175. [NonAction]
  176. public void HashAdd<T>(string key, string hashKey, T value)
  177. {
  178. var hash = GetHashMap<T>(key);
  179. hash.Add(hashKey, value);
  180. }
  181. /// <summary>
  182. /// 获取多条HASH
  183. /// </summary>
  184. /// <typeparam name="T"></typeparam>
  185. /// <param name="key"></param>
  186. /// <param name="fields"></param>
  187. /// <returns></returns>
  188. [NonAction]
  189. public List<T> HashGet<T>(string key, params string[] fields)
  190. {
  191. var hash = GetHashMap<T>(key);
  192. var result = hash.HMGet(fields);
  193. return result.ToList();
  194. }
  195. /// <summary>
  196. /// 获取一条HASH
  197. /// </summary>
  198. /// <typeparam name="T"></typeparam>
  199. /// <param name="key"></param>
  200. /// <param name="field"></param>
  201. /// <returns></returns>
  202. [NonAction]
  203. public T HashGetOne<T>(string key, string field)
  204. {
  205. var hash = GetHashMap<T>(key);
  206. var result = hash.HMGet(new string[] { field });
  207. return result[0];
  208. }
  209. /// <summary>
  210. /// 根据KEY获取所有HASH
  211. /// </summary>
  212. /// <typeparam name="T"></typeparam>
  213. /// <param name="key"></param>
  214. /// <returns></returns>
  215. [NonAction]
  216. public IDictionary<string, T> HashGetAll<T>(string key)
  217. {
  218. var hash = GetHashMap<T>(key);
  219. return hash.GetAll();
  220. }
  221. /// <summary>
  222. /// 删除HASH
  223. /// </summary>
  224. /// <typeparam name="T"></typeparam>
  225. /// <param name="key"></param>
  226. /// <param name="fields"></param>
  227. /// <returns></returns>
  228. [NonAction]
  229. public int HashDel<T>(string key, params string[] fields)
  230. {
  231. var hash = GetHashMap<T>(key);
  232. return hash.HDel(fields);
  233. }
  234. /// <summary>
  235. /// 搜索HASH
  236. /// </summary>
  237. /// <typeparam name="T"></typeparam>
  238. /// <param name="key"></param>
  239. /// <param name="searchModel"></param>
  240. /// <returns></returns>
  241. [NonAction]
  242. public List<KeyValuePair<string, T>> HashSearch<T>(string key, SearchModel searchModel)
  243. {
  244. var hash = GetHashMap<T>(key);
  245. return hash.Search(searchModel).ToList();
  246. }
  247. /// <summary>
  248. /// 搜索HASH
  249. /// </summary>
  250. /// <typeparam name="T"></typeparam>
  251. /// <param name="key"></param>
  252. /// <param name="pattern"></param>
  253. /// <param name="count"></param>
  254. /// <returns></returns>
  255. [NonAction]
  256. public List<KeyValuePair<string, T>> HashSearch<T>(string key, string pattern, int count)
  257. {
  258. var hash = GetHashMap<T>(key);
  259. return hash.Search(pattern, count).ToList();
  260. }
  261. }