CacheHelper.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using Microsoft.AspNetCore.Hosting;
  7. using Microsoft.Extensions.Caching;
  8. using Microsoft.Extensions.Caching.Memory;
  9. namespace WebAPIBase.Utils
  10. {
  11. /// <summary>
  12. /// 缓存操作,默认缓存1分钟
  13. /// </summary>
  14. public class CacheHelper
  15. {
  16. private IMemoryCache _cache;
  17. public CacheHelper(IMemoryCache memoryCache)
  18. {
  19. _cache = memoryCache;
  20. }
  21. /// <summary>
  22. /// 读取缓存项
  23. /// </summary>
  24. /// <returns></returns>
  25. public object GetCache(string cacheKey)
  26. {
  27. return _cache.Get(cacheKey);
  28. }
  29. /// <summary>
  30. /// 写入缓存项
  31. /// </summary>
  32. public void SetCache(string cacheKey, object cacheValue)
  33. {
  34. _cache.Set(cacheKey, cacheValue, new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromHours(2)));
  35. }
  36. /// <summary>.
  37. /// 移除指定缓存项
  38. /// </summary>
  39. public void DelCache(string cacheName)
  40. {
  41. _cache.Remove(cacheName);
  42. }
  43. }
  44. }