You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 line
2.6KB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using Microsoft.Extensions.Caching.Memory;
  7. namespace TelpoPush.Service.Cache
  8. {
  9. internal class MemoryCacheUtil
  10. {
  11. static MemoryCache cache = new MemoryCache(new MemoryCacheOptions());
  12. /// <summary>
  13. /// 创建缓存项的文件
  14. /// </summary>
  15. /// <param name="key">缓存Key</param>
  16. /// <param name="obj">object对象</param>
  17. public static void Set(string key, object value)
  18. {
  19. if (key != null)
  20. {
  21. cache.Set(key, value);
  22. }
  23. }
  24. /// <summary>
  25. /// 创建缓存项过期
  26. /// </summary>
  27. /// <param name="key">缓存Key</param>
  28. /// <param name="obj">object对象</param>
  29. /// <param name="expires">过期时间(秒)</param>
  30. public static void Set(string key, object value, int expires)
  31. {
  32. if (key != null)
  33. {
  34. cache.Set(key, value, new MemoryCacheEntryOptions()
  35. //设置缓存时间,如果被访问重置缓存时间。设置相对过期时间x秒
  36. .SetSlidingExpiration(TimeSpan.FromSeconds(expires)));
  37. }
  38. }
  39. /// <summary>
  40. /// 获取缓存对象
  41. /// </summary>
  42. /// <param name="key">缓存Key</param>
  43. /// <returns>object对象</returns>
  44. public static object Get(string key)
  45. {
  46. object val = null;
  47. if (key != null && cache.TryGetValue(key, out val))
  48. {
  49. return val;
  50. }
  51. else
  52. {
  53. return default(object);
  54. }
  55. }
  56. /// <summary>
  57. /// 获取缓存对象
  58. /// </summary>
  59. /// <typeparam name="T">T对象</typeparam>
  60. /// <param name="key">缓存Key</param>
  61. /// <returns></returns>
  62. public static T Get<T>(string key)
  63. {
  64. object obj = Get(key);
  65. return obj == null ? default(T) : (T)obj;
  66. }
  67. /// <summary>
  68. /// 移除缓存项的文件
  69. /// </summary>
  70. /// <param name="key">缓存Key</param>
  71. public static void Remove(string key)
  72. {
  73. cache.Remove(key);
  74. }
  75. }
  76. }