DataCache.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using System.Runtime.Caching;
  3. namespace SHJX.Service.Common.CustomUtil
  4. {
  5. /// <summary>
  6. /// 数据缓存工具类
  7. /// </summary>
  8. public static class DataCache
  9. {
  10. private static readonly MemoryCache cache = new("ErrorFromEmsCache");
  11. /// <summary>
  12. /// 在缓存中新增数据
  13. /// </summary>
  14. /// <param name="detailInfo"></param>
  15. public static void Set<T>(string key, T value)
  16. {
  17. var policy = new CacheItemPolicy
  18. {
  19. AbsoluteExpiration = DateTime.Now.AddHours(15)
  20. };
  21. if (!Contains(key))
  22. {
  23. cache.Set(key, value, policy);
  24. }
  25. cache[key] = value;
  26. }
  27. /// <summary>
  28. /// 查询缓存中是否包含指定键
  29. /// </summary>
  30. /// <param name="key"></param>
  31. /// <returns></returns>
  32. public static bool Contains(string key)
  33. {
  34. return cache.Contains(key);
  35. }
  36. /// <summary>
  37. /// 获取缓存中数据
  38. /// </summary>
  39. /// <param name="key"></param>
  40. /// <returns></returns>
  41. public static T Get<T>(string key)
  42. {
  43. try
  44. {
  45. if (Contains(key))
  46. {
  47. return (T)cache[key];
  48. }
  49. return default;
  50. }
  51. catch (Exception)
  52. {
  53. return default;
  54. }
  55. }
  56. /// <summary>
  57. /// 移除缓存中的数据
  58. /// </summary>
  59. /// <param name="key"></param>
  60. public static void Remove(string key)
  61. {
  62. if (Contains(key))
  63. {
  64. cache.Remove(key);
  65. }
  66. }
  67. }
  68. }