DataCache.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System;
  2. using SHJX.Service.Common.Logging;
  3. using Microsoft.Extensions.Options;
  4. using Microsoft.Extensions.Logging;
  5. using Microsoft.Extensions.Caching.Memory;
  6. namespace SHJX.Service.Common.Utils
  7. {
  8. /// <summary>
  9. /// 数据缓存工具类
  10. /// </summary>
  11. public class DataCache
  12. {
  13. private static DataCache _cache;
  14. private static readonly object obj_lock = new();
  15. private static readonly ILogger Logger = LogFactory.BuildLogger(typeof(DataCache));
  16. private static readonly MemoryCache cache = new(Options.Create(new MemoryCacheOptions()));
  17. private DataCache() { }
  18. public static DataCache Instance
  19. {
  20. get
  21. {
  22. if (_cache is null)
  23. {
  24. lock (obj_lock)
  25. {
  26. _cache = new DataCache();
  27. }
  28. }
  29. return _cache;
  30. }
  31. }
  32. /// <summary>
  33. /// 新增
  34. /// </summary>
  35. /// <typeparam name="T">缓存类型</typeparam>
  36. /// <param name="key">键</param>
  37. /// <param name="value">值</param>
  38. /// <param name="cacheTime">缓存时间(秒)</param>
  39. public void Set<T>(object key, T value, int cacheTime = 5)
  40. {
  41. cache.GetOrCreate(key, entry =>
  42. {
  43. entry.SetAbsoluteExpiration(TimeSpan.FromSeconds(cacheTime));
  44. entry.RegisterPostEvictionCallback((key, value, reason, state) =>
  45. {
  46. Logger.LogInformation($"{value}已过期");
  47. });
  48. return value;
  49. });
  50. }
  51. /// <summary>
  52. /// 获取缓存中数据
  53. /// </summary>
  54. /// <param name="key"></param>
  55. /// <returns></returns>
  56. public T Get<T>(object key)
  57. {
  58. try
  59. {
  60. if (cache.TryGetValue(key, out var value))
  61. {
  62. return (T)value;
  63. }
  64. return default;
  65. }
  66. catch (Exception)
  67. {
  68. return default;
  69. }
  70. }
  71. /// <summary>
  72. /// 移除缓存中的数据
  73. /// </summary>
  74. /// <param name="key"></param>
  75. public void Remove(object key)
  76. {
  77. if (cache.TryGetValue(key, out _))
  78. {
  79. cache.Remove(key);
  80. }
  81. }
  82. public int Count => cache.Count;
  83. }
  84. }