Нет описания

CacheHelper.cs 3.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Web;
  8. using System.Web.Caching;
  9. namespace CallCenterApi.Common
  10. {
  11. public class CacheHelper
  12. {
  13. /// <summary>
  14. /// 创建缓存项的文件依赖
  15. /// </summary>
  16. /// <param name="key">缓存Key</param>
  17. /// <param name="obj">object对象</param>
  18. /// <param name="fileName">文件绝对路径</param>
  19. public static void Insert(string key, object obj, string fileName)
  20. {
  21. //创建缓存依赖项
  22. CacheDependency dep = new CacheDependency(fileName);
  23. //创建缓存
  24. HttpContext.Current.Cache.Insert(key, obj, dep);
  25. }
  26. /// <summary>
  27. /// 创建缓存,无过期时间
  28. /// </summary>
  29. /// <param name="key"></param>
  30. /// <param name="obj"></param>
  31. public static void Insert(string key, object obj)
  32. {
  33. HttpContext.Current.Cache.Insert(key, obj);
  34. }
  35. /// <summary>
  36. /// 创建缓存项过期
  37. /// </summary>
  38. /// <param name="key">缓存Key</param>
  39. /// <param name="obj">object对象</param>
  40. /// <param name="expires">过期时间(分钟)</param>
  41. public static void Insert(string key, object obj, int expires)
  42. {
  43. HttpContext.Current.Cache.Insert(key, obj, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, expires, 0));
  44. }
  45. /// <summary>
  46. /// 获取缓存对象
  47. /// </summary>
  48. /// <param name="key">缓存Key</param>
  49. /// <returns>object对象</returns>
  50. public static object Get(string key)
  51. {
  52. if (string.IsNullOrEmpty(key))
  53. {
  54. return null;
  55. }
  56. return HttpContext.Current.Cache.Get(key);
  57. }
  58. /// <summary>
  59. /// 获取缓存对象
  60. /// </summary>
  61. /// <typeparam name="T">T对象</typeparam>
  62. /// <param name="key">缓存Key</param>
  63. /// <returns></returns>
  64. public static T Get<T>(string key)
  65. {
  66. object obj = Get(key);
  67. return obj == null ? default(T) : (T)obj;
  68. }
  69. /// <summary>
  70. /// 移出Cache对象
  71. /// </summary>
  72. /// <param name="CacheKey"></param>
  73. public static void Remove(string Key)
  74. {
  75. System.Web.Caching.Cache objCache = HttpRuntime.Cache;
  76. objCache.Remove(Key);
  77. }
  78. /// <summary>
  79. /// 移除所有Cache对象
  80. /// </summary>
  81. public static void RemoveAll()
  82. {
  83. System.Web.Caching.Cache cache = HttpRuntime.Cache;
  84. IDictionaryEnumerator cacheEnum = cache.GetEnumerator();
  85. ArrayList al = new ArrayList();
  86. while (cacheEnum.MoveNext())
  87. {
  88. al.Add(cacheEnum.Key);
  89. }
  90. foreach (string key in al)
  91. {
  92. cache.Remove(key);
  93. }
  94. }
  95. }
  96. }