CancelCache.cs 1.7 KB

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