CacheManager.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using Newtonsoft.Json;
  3. using System.Globalization;
  4. using WingInterfaceLibrary.Enum;
  5. using System.Collections.Concurrent;
  6. namespace WingDeviceService.Common
  7. {
  8. public class CacheManager<TObject> : IDisposable where TObject : class
  9. {
  10. private ConcurrentDictionary<string, TObject> _source = new();
  11. /// <summary>
  12. /// 添加/更新缓存
  13. /// </summary>
  14. /// <param name="key"></param>
  15. /// <param name="obj"></param>
  16. public TObject AddOrUpdate(string key, TObject obj)
  17. {
  18. return _source.AddOrUpdate(key, obj, (k, v) => obj);
  19. }
  20. /// <summary>
  21. /// 删除缓存
  22. /// </summary>
  23. /// <param name="key"></param>
  24. /// <returns></returns>
  25. public bool Remove(string key)
  26. {
  27. return _source.TryRemove(key, out _);
  28. }
  29. /// <summary>
  30. /// 获取缓存信息
  31. /// </summary>
  32. /// <param name="key"></param>
  33. /// <returns></returns>
  34. public TObject Get(string key)
  35. {
  36. if (_source.TryGetValue(key, out TObject obj))
  37. {
  38. return obj;
  39. }
  40. return default;
  41. }
  42. /// <summary>
  43. /// 清空缓存
  44. /// </summary>
  45. public void Dispose()
  46. {
  47. _source.Clear();
  48. }
  49. }
  50. public class CacheManagerSingle<TObject> where TObject : class
  51. {
  52. private CacheManagerSingle() { }
  53. private readonly static object _locker = new();
  54. private static CacheManager<TObject> _instance;
  55. /// <summary>
  56. /// 单例对象
  57. /// </summary>
  58. /// <value></value>
  59. public static CacheManager<TObject> Instance
  60. {
  61. get
  62. {
  63. if (_instance == null)
  64. {
  65. lock (_locker)
  66. {
  67. if (_instance == null)
  68. {
  69. _instance = new CacheManager<TObject>();
  70. }
  71. }
  72. }
  73. return _instance;
  74. }
  75. }
  76. }
  77. }