CacheHelper.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using Newtonsoft.Json;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Runtime.Caching;
  6. using System.Web;
  7. namespace Central.Control.WebApi.Cache
  8. {
  9. /// <summary>
  10. ///
  11. /// </summary>
  12. public class CacheHelper: ICacheHelper
  13. {
  14. private MemoryCache _cache = MemoryCache.Default;
  15. /// <summary>
  16. /// 此方法缓存不会过期,请谨慎使用
  17. /// </summary>
  18. /// <param name="key"></param>
  19. /// <param name="content"></param>
  20. public void SetByNotExpired<T>(string key, T content)
  21. {
  22. var policy = new CacheItemPolicy
  23. {
  24. AbsoluteExpiration = ObjectCache.InfiniteAbsoluteExpiration
  25. };
  26. _cache.Set(key, content, policy);
  27. }
  28. /// <summary>
  29. ///
  30. /// </summary>
  31. /// <param name="key"></param>
  32. /// <param name="content"></param>
  33. /// <param name="seconds"></param>
  34. public void Set<T>(string key, T content, int seconds = 300)
  35. {
  36. var policy = new CacheItemPolicy
  37. {
  38. AbsoluteExpiration = DateTime.Now.AddSeconds(seconds)
  39. };
  40. policy.AbsoluteExpiration = ObjectCache.InfiniteAbsoluteExpiration;
  41. // System.Runtime.Caching.ObjectCache.InfiniteAbsoluteExpiration
  42. _cache.Set(key, content, policy);
  43. }
  44. /// <summary>
  45. ///
  46. /// </summary>
  47. /// <typeparam name="T"></typeparam>
  48. /// <param name="key"></param>
  49. /// <returns></returns>
  50. public T Get<T>(string key) where T : class
  51. {
  52. if (_cache.Contains(key))
  53. {
  54. return _cache[key] as T;
  55. }
  56. return null;
  57. }
  58. /// <summary>
  59. ///
  60. /// </summary>
  61. /// <param name="key"></param>
  62. public void Remove(string key)
  63. {
  64. _cache.Remove(key);
  65. }
  66. }
  67. }