SysCacheService.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. // Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
  2. //
  3. // 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
  4. //
  5. // 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
  6. using NewLife.Reflection;
  7. using Newtonsoft.Json;
  8. namespace Admin.NET.Core.Service;
  9. /// <summary>
  10. /// 系统缓存服务 🧩
  11. /// </summary>
  12. [ApiDescriptionSettings(Order = 400)]
  13. public class SysCacheService : IDynamicApiController, ISingleton
  14. {
  15. private static ICacheProvider _cacheProvider;
  16. private readonly CacheOptions _cacheOptions;
  17. public SysCacheService(ICacheProvider cacheProvider, IOptions<CacheOptions> cacheOptions)
  18. {
  19. _cacheProvider = cacheProvider;
  20. _cacheOptions = cacheOptions.Value;
  21. }
  22. /// <summary>
  23. /// 申请分布式锁
  24. /// </summary>
  25. /// <param name="key">要锁定的key</param>
  26. /// <param name="msTimeout">申请锁等待的时间,单位毫秒</param>
  27. /// <param name="msExpire">锁过期时间,超过该时间没有主动是放则自动是放,必须整数秒,单位毫秒</param>
  28. /// <param name="throwOnFailure">失败时是否抛出异常,如不抛出异常,可通过判断返回null得知申请锁失败</param>
  29. /// <returns></returns>
  30. [DisplayName("申请分布式锁")]
  31. public IDisposable? BeginCacheLock(string key, int msTimeout = 500, int msExpire = 10000, bool throwOnFailure = true)
  32. {
  33. try
  34. {
  35. return _cacheProvider.Cache.AcquireLock(key, msTimeout, msExpire, throwOnFailure);
  36. }
  37. catch
  38. {
  39. return null;
  40. }
  41. }
  42. /// <summary>
  43. /// 获取缓存键名集合 🔖
  44. /// </summary>
  45. /// <returns></returns>
  46. [DisplayName("获取缓存键名集合")]
  47. public List<string> GetKeyList()
  48. {
  49. return _cacheProvider.Cache == Cache.Default
  50. ? _cacheProvider.Cache.Keys.Where(u => u.StartsWith(_cacheOptions.Prefix)).Select(u => u[_cacheOptions.Prefix.Length..]).OrderBy(u => u).ToList()
  51. : ((FullRedis)_cacheProvider.Cache).Search($"{_cacheOptions.Prefix}*", int.MaxValue).Select(u => u[_cacheOptions.Prefix.Length..]).OrderBy(u => u).ToList();
  52. }
  53. /// <summary>
  54. /// 增加缓存
  55. /// </summary>
  56. /// <param name="key"></param>
  57. /// <param name="value"></param>
  58. /// <returns></returns>
  59. [NonAction]
  60. public bool Set(string key, object value)
  61. {
  62. return !string.IsNullOrWhiteSpace(key) && _cacheProvider.Cache.Set($"{_cacheOptions.Prefix}{key}", value);
  63. }
  64. /// <summary>
  65. /// 增加缓存并设置过期时间
  66. /// </summary>
  67. /// <param name="key"></param>
  68. /// <param name="value"></param>
  69. /// <param name="expire"></param>
  70. /// <returns></returns>
  71. [NonAction]
  72. public bool Set(string key, object value, TimeSpan expire)
  73. {
  74. return !string.IsNullOrWhiteSpace(key) && _cacheProvider.Cache.Set($"{_cacheOptions.Prefix}{key}", value, expire);
  75. }
  76. public async Task<TR> AdGetAsync<TR>(String cacheName, Func<Task<TR>> del, TimeSpan? expiry = default(TimeSpan?)) where TR : class
  77. {
  78. return await AdGetAsync<TR>(cacheName, del, new object[] { }, expiry);
  79. }
  80. public async Task<TR> AdGetAsync<TR, T1>(String cacheName, Func<T1, Task<TR>> del, T1 t1, TimeSpan? expiry = default(TimeSpan?)) where TR : class
  81. {
  82. return await AdGetAsync<TR>(cacheName, del, new object[] { t1 }, expiry);
  83. }
  84. public async Task<TR> AdGetAsync<TR, T1, T2>(String cacheName, Func<T1, T2, Task<TR>> del, T1 t1, T2 t2, TimeSpan? expiry = default(TimeSpan?)) where TR : class
  85. {
  86. return await AdGetAsync<TR>(cacheName, del, new object[] { t1, t2 }, expiry);
  87. }
  88. public async Task<TR> AdGetAsync<TR, T1, T2, T3>(String cacheName, Func<T1, T2, T3, Task<TR>> del, T1 t1, T2 t2, T3 t3, TimeSpan? expiry = default(TimeSpan?)) where TR : class
  89. {
  90. return await AdGetAsync<TR>(cacheName, del, new object[] { t1, t2, t3 }, expiry);
  91. }
  92. private async Task<T> AdGetAsync<T>(string cacheName, Delegate del, Object[] obs, TimeSpan? expiry) where T : class
  93. {
  94. var key = Key(cacheName, obs);
  95. // 使用分布式锁
  96. using (_cacheProvider.Cache.AcquireLock($@"lock:AdGetAsync:{cacheName}", 1000))
  97. {
  98. var value = Get<T>(key);
  99. value ??= await ((dynamic)del).DynamicInvokeAsync(obs);
  100. Set(key, value);
  101. return value;
  102. }
  103. }
  104. public T Get<T>(String cacheName, object t1)
  105. {
  106. return Get<T>(cacheName, new object[] { t1 });
  107. }
  108. public T Get<T>(String cacheName, object t1, object t2)
  109. {
  110. return Get<T>(cacheName, new object[] { t1, t2 });
  111. }
  112. public T Get<T>(String cacheName, object t1, object t2, object t3)
  113. {
  114. return Get<T>(cacheName, new object[] { t1, t2, t3 });
  115. }
  116. private T Get<T>(String cacheName, Object[] obs)
  117. {
  118. var key = cacheName + ":" + obs.Aggregate(string.Empty, (current, o) => current + $"<{o}>");
  119. return Get<T>(key);
  120. }
  121. private static string Key(string cacheName, object[] obs)
  122. {
  123. if (obs.OfType<TimeSpan>().Any()) throw new Exception("缓存参数类型不能能是:TimeSpan类型");
  124. StringBuilder sb = new (cacheName + ":");
  125. foreach (var a in obs) sb.Append($"<{KeySingle(a)}>");
  126. return sb.ToString();
  127. }
  128. private static string KeySingle(object t)
  129. {
  130. return t.GetType().IsClass && !t.GetType().IsPrimitive ? JsonConvert.SerializeObject(t) : t.ToString();
  131. }
  132. /// <summary>
  133. /// 获取缓存的剩余生存时间
  134. /// </summary>
  135. /// <param name="key"></param>
  136. /// <returns></returns>
  137. [NonAction]
  138. public TimeSpan GetExpire(string key)
  139. {
  140. return _cacheProvider.Cache.GetExpire(key);
  141. }
  142. /// <summary>
  143. /// 获取缓存
  144. /// </summary>
  145. /// <typeparam name="T"></typeparam>
  146. /// <param name="key"></param>
  147. /// <returns></returns>
  148. [NonAction]
  149. public T Get<T>(string key)
  150. {
  151. return _cacheProvider.Cache.Get<T>($"{_cacheOptions.Prefix}{key}");
  152. }
  153. /// <summary>
  154. /// 删除缓存 🔖
  155. /// </summary>
  156. /// <param name="key"></param>
  157. /// <returns></returns>
  158. [ApiDescriptionSettings(Name = "Delete"), HttpPost]
  159. [DisplayName("删除缓存")]
  160. public int Remove(string key)
  161. {
  162. return _cacheProvider.Cache.Remove($"{_cacheOptions.Prefix}{key}");
  163. }
  164. /// <summary>
  165. /// 清空所有缓存 🔖
  166. /// </summary>
  167. /// <returns></returns>
  168. [DisplayName("清空所有缓存")]
  169. [ApiDescriptionSettings(Name = "Clear"), HttpPost]
  170. public void Clear()
  171. {
  172. _cacheProvider.Cache.Clear();
  173. Cache.Default.Clear();
  174. }
  175. /// <summary>
  176. /// 检查缓存是否存在
  177. /// </summary>
  178. /// <param name="key">键</param>
  179. /// <returns></returns>
  180. [NonAction]
  181. public bool ExistKey(string key)
  182. {
  183. return _cacheProvider.Cache.ContainsKey($"{_cacheOptions.Prefix}{key}");
  184. }
  185. /// <summary>
  186. /// 根据键名前缀删除缓存 🔖
  187. /// </summary>
  188. /// <param name="prefixKey">键名前缀</param>
  189. /// <returns></returns>
  190. [ApiDescriptionSettings(Name = "DeleteByPreKey"), HttpPost]
  191. [DisplayName("根据键名前缀删除缓存")]
  192. public int RemoveByPrefixKey(string prefixKey)
  193. {
  194. var delKeys = _cacheProvider.Cache == Cache.Default
  195. ? _cacheProvider.Cache.Keys.Where(u => u.StartsWith($"{_cacheOptions.Prefix}{prefixKey}")).ToArray()
  196. : ((FullRedis)_cacheProvider.Cache).Search($"{_cacheOptions.Prefix}{prefixKey}*", int.MaxValue).ToArray();
  197. return _cacheProvider.Cache.Remove(delKeys);
  198. }
  199. /// <summary>
  200. /// 根据键名前缀获取键名集合 🔖
  201. /// </summary>
  202. /// <param name="prefixKey">键名前缀</param>
  203. /// <returns></returns>
  204. [DisplayName("根据键名前缀获取键名集合")]
  205. public List<string> GetKeysByPrefixKey(string prefixKey)
  206. {
  207. return _cacheProvider.Cache == Cache.Default
  208. ? _cacheProvider.Cache.Keys.Where(u => u.StartsWith($"{_cacheOptions.Prefix}{prefixKey}")).Select(u => u[_cacheOptions.Prefix.Length..]).ToList()
  209. : ((FullRedis)_cacheProvider.Cache).Search($"{_cacheOptions.Prefix}{prefixKey}*", int.MaxValue).Select(u => u[_cacheOptions.Prefix.Length..]).ToList();
  210. }
  211. /// <summary>
  212. /// 获取缓存值 🔖
  213. /// </summary>
  214. /// <param name="key"></param>
  215. /// <returns></returns>
  216. [DisplayName("获取缓存值")]
  217. public object GetValue(string key)
  218. {
  219. // 若Key经过URL编码则进行解码
  220. if (Regex.IsMatch(key, @"%[0-9a-fA-F]{2}"))
  221. key = HttpUtility.UrlDecode(key);
  222. return _cacheProvider.Cache == Cache.Default
  223. ? _cacheProvider.Cache.Get<object>($"{_cacheOptions.Prefix}{key}")
  224. : _cacheProvider.Cache.Get<string>($"{_cacheOptions.Prefix}{key}");
  225. }
  226. /// <summary>
  227. /// 获取或添加缓存(在数据不存在时执行委托请求数据)
  228. /// </summary>
  229. /// <typeparam name="T"></typeparam>
  230. /// <param name="key"></param>
  231. /// <param name="callback"></param>
  232. /// <param name="expire">过期时间,单位秒</param>
  233. /// <returns></returns>
  234. [NonAction]
  235. public T GetOrAdd<T>(string key, Func<string, T> callback, int expire = -1)
  236. {
  237. if (string.IsNullOrWhiteSpace(key)) return default;
  238. return _cacheProvider.Cache.GetOrAdd($"{_cacheOptions.Prefix}{key}", callback, expire);
  239. }
  240. /// <summary>
  241. /// Hash匹配
  242. /// </summary>
  243. /// <typeparam name="T"></typeparam>
  244. /// <param name="key"></param>
  245. /// <returns></returns>
  246. [NonAction]
  247. public IDictionary<String, T> GetHashMap<T>(string key)
  248. {
  249. return _cacheProvider.Cache.GetDictionary<T>(key);
  250. }
  251. /// <summary>
  252. /// 批量添加HASH
  253. /// </summary>
  254. /// <typeparam name="T"></typeparam>
  255. /// <param name="key"></param>
  256. /// <param name="dic"></param>
  257. /// <returns></returns>
  258. [NonAction]
  259. public bool HashSet<T>(string key, Dictionary<string, T> dic)
  260. {
  261. var hash = GetHashMap<T>(key);
  262. foreach (var v in dic)
  263. {
  264. hash.Add(v);
  265. }
  266. return true;
  267. }
  268. /// <summary>
  269. /// 添加一条HASH
  270. /// </summary>
  271. /// <typeparam name="T"></typeparam>
  272. /// <param name="key"></param>
  273. /// <param name="hashKey"></param>
  274. /// <param name="value"></param>
  275. [NonAction]
  276. public void HashAdd<T>(string key, string hashKey, T value)
  277. {
  278. var hash = GetHashMap<T>(key);
  279. hash.Add(hashKey, value);
  280. }
  281. /// <summary>
  282. /// 添加或更新一条HASH
  283. /// </summary>
  284. /// <typeparam name="T"></typeparam>
  285. /// <param name="key"></param>
  286. /// <param name="hashKey"></param>
  287. /// <param name="value"></param>
  288. [NonAction]
  289. public void HashAddOrUpdate<T>(string key, string hashKey, T value)
  290. {
  291. var hash = GetHashMap<T>(key);
  292. if (hash.ContainsKey(hashKey))
  293. {
  294. hash[hashKey] = value;
  295. }
  296. else
  297. hash.Add(hashKey, value);
  298. }
  299. /// <summary>
  300. /// 获取多条HASH
  301. /// </summary>
  302. /// <typeparam name="T"></typeparam>
  303. /// <param name="key"></param>
  304. /// <param name="fields"></param>
  305. /// <returns></returns>
  306. [NonAction]
  307. public List<T> HashGet<T>(string key, params string[] fields)
  308. {
  309. var hash = GetHashMap<T>(key);
  310. return hash.Where(t => fields.Any(c => t.Key == c)).Select(t => t.Value).ToList();
  311. }
  312. /// <summary>
  313. /// 获取一条HASH
  314. /// </summary>
  315. /// <typeparam name="T"></typeparam>
  316. /// <param name="key"></param>
  317. /// <param name="field"></param>
  318. /// <returns></returns>
  319. [NonAction]
  320. public T HashGetOne<T>(string key, string field)
  321. {
  322. var hash = GetHashMap<T>(key);
  323. return hash.ContainsKey(field) ? hash[field] : default(T);
  324. }
  325. /// <summary>
  326. /// 根据KEY获取所有HASH
  327. /// </summary>
  328. /// <typeparam name="T"></typeparam>
  329. /// <param name="key"></param>
  330. /// <returns></returns>
  331. [NonAction]
  332. public IDictionary<string, T> HashGetAll<T>(string key)
  333. {
  334. var hash = GetHashMap<T>(key);
  335. return hash;
  336. }
  337. /// <summary>
  338. /// 删除HASH
  339. /// </summary>
  340. /// <typeparam name="T"></typeparam>
  341. /// <param name="key"></param>
  342. /// <param name="fields"></param>
  343. /// <returns></returns>
  344. [NonAction]
  345. public int HashDel<T>(string key, params string[] fields)
  346. {
  347. var hash = GetHashMap<T>(key);
  348. fields.ToList().ForEach(t => hash.Remove(t));
  349. return fields.Length;
  350. }
  351. ///// <summary>
  352. ///// 搜索HASH
  353. ///// </summary>
  354. ///// <typeparam name="T"></typeparam>
  355. ///// <param name="key"></param>
  356. ///// <param name="searchModel"></param>
  357. ///// <returns></returns>
  358. //[NonAction]
  359. //public List<KeyValuePair<string, T>> HashSearch<T>(string key, SearchModel searchModel)
  360. //{
  361. // var hash = GetHashMap<T>(key);
  362. // return hash.Search(searchModel).ToList();
  363. //}
  364. ///// <summary>
  365. ///// 搜索HASH
  366. ///// </summary>
  367. ///// <typeparam name="T"></typeparam>
  368. ///// <param name="key"></param>
  369. ///// <param name="pattern"></param>
  370. ///// <param name="count"></param>
  371. ///// <returns></returns>
  372. //[NonAction]
  373. //public List<KeyValuePair<string, T>> HashSearch<T>(string key, string pattern, int count)
  374. //{
  375. // var hash = GetHashMap<T>(key);
  376. // return hash.Search(pattern, count).ToList();
  377. //}
  378. }