市长热线演示版

CacheHelper.cs 3.0KB

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