SysCacheService.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. // 麻省理工学院许可证
  2. //
  3. // 版权所有 (c) 2021-2023 zuohuaijun,大名科技(天津)有限公司 联系电话/微信:18020030720 QQ:515096995
  4. //
  5. // 特此免费授予获得本软件的任何人以处理本软件的权利,但须遵守以下条件:在所有副本或重要部分的软件中必须包括上述版权声明和本许可声明。
  6. //
  7. // 软件按“原样”提供,不提供任何形式的明示或暗示的保证,包括但不限于对适销性、适用性和非侵权的保证。
  8. // 在任何情况下,作者或版权持有人均不对任何索赔、损害或其他责任负责,无论是因合同、侵权或其他方式引起的,与软件或其使用或其他交易有关。
  9. using NewLife.Caching.Models;
  10. namespace Admin.NET.Core.Service;
  11. /// <summary>
  12. /// 系统缓存服务
  13. /// </summary>
  14. [ApiDescriptionSettings(Order = 400)]
  15. public class SysCacheService : IDynamicApiController, ISingleton
  16. {
  17. private readonly ICache _cache;
  18. private readonly CacheOptions _cacheOptions;
  19. public SysCacheService(ICache cache, IOptions<CacheOptions> cacheOptions)
  20. {
  21. _cache = cache;
  22. _cacheOptions = cacheOptions.Value;
  23. }
  24. /// <summary>
  25. /// 获取缓存键名集合
  26. /// </summary>
  27. /// <returns></returns>
  28. [DisplayName("获取缓存键名集合")]
  29. public List<string> GetKeyList()
  30. {
  31. return _cache == Cache.Default
  32. ? _cache.Keys.Where(u => u.StartsWith(_cacheOptions.Prefix)).Select(u => u[_cacheOptions.Prefix.Length..]).OrderBy(u => u).ToList()
  33. : ((FullRedis)_cache).Search($"{_cacheOptions.Prefix}*", int.MaxValue).Select(u => u[_cacheOptions.Prefix.Length..]).OrderBy(u => u).ToList();
  34. }
  35. /// <summary>
  36. /// 增加缓存
  37. /// </summary>
  38. /// <param name="key"></param>
  39. /// <param name="value"></param>
  40. /// <returns></returns>
  41. [NonAction]
  42. public bool Set(string key, object value)
  43. {
  44. if (string.IsNullOrWhiteSpace(key)) return false;
  45. return _cache.Set($"{_cacheOptions.Prefix}{key}", value);
  46. }
  47. /// <summary>
  48. /// 增加缓存并设置过期时间
  49. /// </summary>
  50. /// <param name="key"></param>
  51. /// <param name="value"></param>
  52. /// <param name="expire"></param>
  53. /// <returns></returns>
  54. [NonAction]
  55. public bool Set(string key, object value, TimeSpan expire)
  56. {
  57. if (string.IsNullOrWhiteSpace(key)) return false;
  58. return _cache.Set($"{_cacheOptions.Prefix}{key}", value, expire);
  59. }
  60. /// <summary>
  61. /// 获取缓存
  62. /// </summary>
  63. /// <typeparam name="T"></typeparam>
  64. /// <param name="key"></param>
  65. /// <returns></returns>
  66. [NonAction]
  67. public T Get<T>(string key)
  68. {
  69. return _cache.Get<T>($"{_cacheOptions.Prefix}{key}");
  70. }
  71. /// <summary>
  72. /// 删除缓存
  73. /// </summary>
  74. /// <param name="key"></param>
  75. /// <returns></returns>
  76. [ApiDescriptionSettings(Name = "Delete"), HttpPost]
  77. [DisplayName("删除缓存")]
  78. public int Remove(string key)
  79. {
  80. return _cache.Remove($"{_cacheOptions.Prefix}{key}");
  81. }
  82. /// <summary>
  83. /// 检查缓存是否存在
  84. /// </summary>
  85. /// <param name="key">键</param>
  86. /// <returns></returns>
  87. [NonAction]
  88. public bool ExistKey(string key)
  89. {
  90. return _cache.ContainsKey($"{_cacheOptions.Prefix}{key}");
  91. }
  92. /// <summary>
  93. /// 根据键名前缀删除缓存
  94. /// </summary>
  95. /// <param name="prefixKey">键名前缀</param>
  96. /// <returns></returns>
  97. [ApiDescriptionSettings(Name = "DeleteByPreKey"), HttpPost]
  98. [DisplayName("根据键名前缀删除缓存")]
  99. public int RemoveByPrefixKey(string prefixKey)
  100. {
  101. var delKeys = _cache == Cache.Default
  102. ? _cache.Keys.Where(u => u.StartsWith($"{_cacheOptions.Prefix}{prefixKey}")).ToArray()
  103. : ((FullRedis)_cache).Search($"{_cacheOptions.Prefix}{prefixKey}*", int.MaxValue).ToArray();
  104. return _cache.Remove(delKeys);
  105. }
  106. /// <summary>
  107. /// 根据键名前缀获取键名集合
  108. /// </summary>
  109. /// <param name="prefixKey">键名前缀</param>
  110. /// <returns></returns>
  111. [DisplayName("根据键名前缀获取键名集合")]
  112. public List<string> GetKeysByPrefixKey(string prefixKey)
  113. {
  114. return _cache == Cache.Default
  115. ? _cache.Keys.Where(u => u.StartsWith($"{_cacheOptions.Prefix}{prefixKey}")).Select(u => u[_cacheOptions.Prefix.Length..]).ToList()
  116. : ((FullRedis)_cache).Search($"{_cacheOptions.Prefix}{prefixKey}*", int.MaxValue).Select(u => u[_cacheOptions.Prefix.Length..]).ToList();
  117. }
  118. /// <summary>
  119. /// 获取缓存值
  120. /// </summary>
  121. /// <param name="key"></param>
  122. /// <returns></returns>
  123. [DisplayName("获取缓存值")]
  124. public object GetValue(string key)
  125. {
  126. return _cache == Cache.Default
  127. ? _cache.Get<object>($"{_cacheOptions.Prefix}{key}")
  128. : _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 _cache.GetOrAdd($"{_cacheOptions.Prefix}{key}", callback, expire);
  143. }
  144. [NonAction]
  145. public RedisHash<string, T> GetHashMap<T>(string key)
  146. {
  147. return _cache.GetDictionary<T>(key) as RedisHash<string, T>;
  148. }
  149. /// <summary>
  150. /// 批量添加HASH
  151. /// </summary>
  152. /// <typeparam name="T"></typeparam>
  153. /// <param name="key"></param>
  154. /// <param name="dic"></param>
  155. /// <returns></returns>
  156. [NonAction]
  157. public bool HashSet<T>(string key, Dictionary<string, T> dic)
  158. {
  159. var hash = GetHashMap<T>(key);
  160. return hash.HMSet(dic);
  161. }
  162. /// <summary>
  163. /// 添加一条HASH
  164. /// </summary>
  165. /// <typeparam name="T"></typeparam>
  166. /// <param name="key"></param>
  167. /// <param name="hashKey"></param>
  168. /// <param name="value"></param>
  169. [NonAction]
  170. public void HashAdd<T>(string key, string hashKey, T value)
  171. {
  172. var hash = GetHashMap<T>(key);
  173. hash.Add(hashKey, value);
  174. }
  175. /// <summary>
  176. /// 获取多条HASH
  177. /// </summary>
  178. /// <typeparam name="T"></typeparam>
  179. /// <param name="key"></param>
  180. /// <param name="fields"></param>
  181. /// <returns></returns>
  182. [NonAction]
  183. public List<T> HashGet<T>(string key, params string[] fields)
  184. {
  185. var hash = GetHashMap<T>(key);
  186. var result = hash.HMGet(fields);
  187. return result.ToList();
  188. }
  189. /// <summary>
  190. /// 获取一条HASH
  191. /// </summary>
  192. /// <typeparam name="T"></typeparam>
  193. /// <param name="key"></param>
  194. /// <param name="field"></param>
  195. /// <returns></returns>
  196. [NonAction]
  197. public T HashGetOne<T>(string key, string field)
  198. {
  199. var hash = GetHashMap<T>(key);
  200. var result = hash.HMGet(new string[] { field });
  201. return result[0];
  202. }
  203. /// <summary>
  204. /// 根据KEY获取所有HASH
  205. /// </summary>
  206. /// <typeparam name="T"></typeparam>
  207. /// <param name="key"></param>
  208. /// <returns></returns>
  209. [NonAction]
  210. public IDictionary<string, T> HashGetAll<T>(string key)
  211. {
  212. var hash = GetHashMap<T>(key);
  213. return hash.GetAll();
  214. }
  215. /// <summary>
  216. /// 删除HASH
  217. /// </summary>
  218. /// <typeparam name="T"></typeparam>
  219. /// <param name="key"></param>
  220. /// <param name="fields"></param>
  221. /// <returns></returns>
  222. [NonAction]
  223. public int HashDel<T>(string key, params string[] fields)
  224. {
  225. var hash = GetHashMap<T>(key);
  226. return hash.HDel(fields);
  227. }
  228. /// <summary>
  229. /// 搜索HASH
  230. /// </summary>
  231. /// <typeparam name="T"></typeparam>
  232. /// <param name="key"></param>
  233. /// <param name="searchModel"></param>
  234. /// <returns></returns>
  235. [NonAction]
  236. public List<KeyValuePair<string, T>> HashSearch<T>(string key, SearchModel searchModel)
  237. {
  238. var hash = GetHashMap<T>(key);
  239. return hash.Search(searchModel).ToList();
  240. }
  241. /// <summary>
  242. /// 搜索HASH
  243. /// </summary>
  244. /// <typeparam name="T"></typeparam>
  245. /// <param name="key"></param>
  246. /// <param name="pattern"></param>
  247. /// <param name="count"></param>
  248. /// <returns></returns>
  249. [NonAction]
  250. public List<KeyValuePair<string, T>> HashSearch<T>(string key, string pattern, int count)
  251. {
  252. var hash = GetHashMap<T>(key);
  253. return hash.Search(pattern, count).ToList();
  254. }
  255. }