WebCache.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System;
  2. using System.Collections;
  3. using System.Web;
  4. namespace Cache
  5. {
  6. /// <summary>
  7. /// 缓存操作
  8. /// </summary>
  9. public class WebCache : ICache
  10. {
  11. private static readonly System.Web.Caching.Cache cache = HttpRuntime.Cache;
  12. /// <summary>
  13. /// 读取缓存
  14. /// </summary>
  15. /// <param name="cacheKey">键</param>
  16. /// <returns></returns>
  17. public T GetCache<T>(string cacheKey) where T : class
  18. {
  19. if (cache[cacheKey] != null)
  20. {
  21. return (T)cache[cacheKey];
  22. }
  23. return default(T);
  24. }
  25. /// <summary>
  26. /// 写入缓存
  27. /// </summary>
  28. /// <param name="value">对象数据</param>
  29. /// <param name="cacheKey">键</param>
  30. public void WriteCache<T>(T value, string cacheKey) where T : class
  31. {
  32. cache.Insert(cacheKey, value, null, DateTime.Now.AddMinutes(10), System.Web.Caching.Cache.NoSlidingExpiration);
  33. }
  34. /// <summary>
  35. /// 写入缓存
  36. /// </summary>
  37. /// <param name="value">对象数据</param>
  38. /// <param name="cacheKey">键</param>
  39. /// <param name="expireTime">到期时间</param>
  40. public void WriteCache<T>(T value, string cacheKey, DateTime expireTime) where T : class
  41. {
  42. cache.Insert(cacheKey, value, null, expireTime, System.Web.Caching.Cache.NoSlidingExpiration);
  43. }
  44. /// <summary>
  45. /// 移除指定数据缓存
  46. /// </summary>
  47. /// <param name="cacheKey">键</param>
  48. public void RemoveCache(string cacheKey)
  49. {
  50. if (cacheKey.Equals("All"))
  51. {
  52. this.RemoveCache();
  53. }
  54. else
  55. {
  56. cache.Remove(cacheKey);
  57. }
  58. }
  59. /// <summary>
  60. /// 移除全部缓存
  61. /// </summary>
  62. public void RemoveCache()
  63. {
  64. IDictionaryEnumerator cacheEnum = cache.GetEnumerator();
  65. while (cacheEnum.MoveNext())
  66. {
  67. if (cacheEnum.Key != null) cache.Remove(cacheEnum.Key.ToString());
  68. }
  69. }
  70. }
  71. }