CacheService.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using Microsoft.Extensions.Logging;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Threading.Tasks;
  8. using ZhonTai.Admin.Core.Attributes;
  9. using ZhonTai.Admin.Core.Configs;
  10. using ZhonTai.DynamicApi;
  11. using ZhonTai.DynamicApi.Attributes;
  12. using ZhonTai.Admin.Core.Consts;
  13. using ZhonTai.Common.Helpers;
  14. namespace ZhonTai.Admin.Services.Cache;
  15. /// <summary>
  16. /// 缓存服务
  17. /// </summary>
  18. [Order(80)]
  19. [DynamicApi(Area = AdminConsts.AreaName)]
  20. public class CacheService : BaseService, ICacheService, IDynamicApi
  21. {
  22. public CacheService()
  23. {
  24. }
  25. /// <summary>
  26. /// 查询列表
  27. /// </summary>
  28. /// <returns></returns>
  29. public List<dynamic> GetList()
  30. {
  31. var list = new List<dynamic>();
  32. var appConfig = LazyGetRequiredService<AppConfig>();
  33. Assembly[] assemblies = AssemblyHelper.GetAssemblyList(appConfig.AssemblyNames);
  34. foreach (Assembly assembly in assemblies)
  35. {
  36. var types = assembly.GetExportedTypes().Where(a => a.GetCustomAttribute<ScanCacheKeysAttribute>() != null);
  37. foreach (Type type in types)
  38. {
  39. var fields = type.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
  40. foreach (FieldInfo field in fields)
  41. {
  42. var descriptionAttribute = field.GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault() as DescriptionAttribute;
  43. list.Add(new
  44. {
  45. field.Name,
  46. Value = field.GetRawConstantValue().ToString(),
  47. descriptionAttribute?.Description
  48. });
  49. }
  50. }
  51. }
  52. return list;
  53. }
  54. /// <summary>
  55. /// 清除缓存
  56. /// </summary>
  57. /// <param name="cacheKey">缓存键</param>
  58. /// <returns></returns>
  59. public async Task ClearAsync(string cacheKey)
  60. {
  61. Logger.LogWarning($"{User.Id}.{User.UserName}清除缓存[{cacheKey}]");
  62. await Cache.DelByPatternAsync(cacheKey + "*");
  63. }
  64. }