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. if (key.Contains('%'))
  124. {
  125. key = HttpUtility.UrlDecode(key);
  126. }
  127. return _cacheProvider.Cache == Cache.Default
  128. ? _cacheProvider.Cache.Get<object>($"{_cacheOptions.Prefix}{key}")
  129. : _cacheProvider.Cache.Get<string>($"{_cacheOptions.Prefix}{key}");
  130. }
  131. /// <summary>
  132. /// 获取或添加缓存(在数据不存在时执行委托请求数据)
  133. /// </summary>
  134. /// <typeparam name="T"></typeparam>
  135. /// <param name="key"></param>
  136. /// <param name="callback"></param>
  137. /// <param name="expire">过期时间,单位秒</param>
  138. /// <returns></returns>
  139. [NonAction]
  140. public T GetOrAdd<T>(string key, Func<string, T> callback, int expire = -1)
  141. {
  142. if (string.IsNullOrWhiteSpace(key)) return default;
  143. return _cacheProvider.Cache.GetOrAdd($"{_cacheOptions.Prefix}{key}", callback, expire);
  144. }
  145. /// <summary>
  146. /// Hash匹配
  147. /// </summary>
  148. /// <typeparam name="T"></typeparam>
  149. /// <param name="key"></param>
  150. /// <returns></returns>
  151. [NonAction]
  152. public RedisHash<string, T> GetHashMap<T>(string key)
  153. {
  154. return _cacheProvider.Cache.GetDictionary<T>(key) as RedisHash<string, T>;
  155. }
  156. /// <summary>
  157. /// 批量添加HASH
  158. /// </summary>
  159. /// <typeparam name="T"></typeparam>
  160. /// <param name="key"></param>
  161. /// <param name="dic"></param>
  162. /// <returns></returns>
  163. [NonAction]
  164. public bool HashSet<T>(string key, Dictionary<string, T> dic)
  165. {
  166. var hash = GetHashMap<T>(key);
  167. return hash.HMSet(dic);
  168. }
  169. /// <summary>
  170. /// 添加一条HASH
  171. /// </summary>
  172. /// <typeparam name="T"></typeparam>
  173. /// <param name="key"></param>
  174. /// <param name="hashKey"></param>
  175. /// <param name="value"></param>
  176. [NonAction]
  177. public void HashAdd<T>(string key, string hashKey, T value)
  178. {
  179. var hash = GetHashMap<T>(key);
  180. hash.Add(hashKey, value);
  181. }
  182. /// <summary>
  183. /// 获取多条HASH
  184. /// </summary>
  185. /// <typeparam name="T"></typeparam>
  186. /// <param name="key"></param>
  187. /// <param name="fields"></param>
  188. /// <returns></returns>
  189. [NonAction]
  190. public List<T> HashGet<T>(string key, params string[] fields)
  191. {
  192. var hash = GetHashMap<T>(key);
  193. var result = hash.HMGet(fields);
  194. return result.ToList();
  195. }
  196. /// <summary>
  197. /// 获取一条HASH
  198. /// </summary>
  199. /// <typeparam name="T"></typeparam>
  200. /// <param name="key"></param>
  201. /// <param name="field"></param>
  202. /// <returns></returns>
  203. [NonAction]
  204. public T HashGetOne<T>(string key, string field)
  205. {
  206. var hash = GetHashMap<T>(key);
  207. var result = hash.HMGet(new string[] { field });
  208. return result[0];
  209. }
  210. /// <summary>
  211. /// 根据KEY获取所有HASH
  212. /// </summary>
  213. /// <typeparam name="T"></typeparam>
  214. /// <param name="key"></param>
  215. /// <returns></returns>
  216. [NonAction]
  217. public IDictionary<string, T> HashGetAll<T>(string key)
  218. {
  219. var hash = GetHashMap<T>(key);
  220. return hash.GetAll();
  221. }
  222. /// <summary>
  223. /// 删除HASH
  224. /// </summary>
  225. /// <typeparam name="T"></typeparam>
  226. /// <param name="key"></param>
  227. /// <param name="fields"></param>
  228. /// <returns></returns>
  229. [NonAction]
  230. public int HashDel<T>(string key, params string[] fields)
  231. {
  232. var hash = GetHashMap<T>(key);
  233. return hash.HDel(fields);
  234. }
  235. /// <summary>
  236. /// 搜索HASH
  237. /// </summary>
  238. /// <typeparam name="T"></typeparam>
  239. /// <param name="key"></param>
  240. /// <param name="searchModel"></param>
  241. /// <returns></returns>
  242. [NonAction]
  243. public List<KeyValuePair<string, T>> HashSearch<T>(string key, SearchModel searchModel)
  244. {
  245. var hash = GetHashMap<T>(key);
  246. return hash.Search(searchModel).ToList();
  247. }
  248. /// <summary>
  249. /// 搜索HASH
  250. /// </summary>
  251. /// <typeparam name="T"></typeparam>
  252. /// <param name="key"></param>
  253. /// <param name="pattern"></param>
  254. /// <param name="count"></param>
  255. /// <returns></returns>
  256. [NonAction]
  257. public List<KeyValuePair<string, T>> HashSearch<T>(string key, string pattern, int count)
  258. {
  259. var hash = GetHashMap<T>(key);
  260. return hash.Search(pattern, count).ToList();
  261. }
  262. }