1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Web;
    5. using System.Web.Caching;
    6. public class CacheHelper
    7. {
    8. /// <summary>
    9. /// 获取数据缓存
    10. /// </summary>
    11. /// <param name="cacheKey">键</param>
    12. public static object GetCache(string cacheKey)
    13. {
    14. var objCache = HttpRuntime.Cache.Get(cacheKey);
    15. return objCache;
    16. }
    17. /// <summary>
    18. /// 设置数据缓存
    19. /// </summary>
    20. public static void SetCache(string cacheKey, object objObject)
    21. {
    22. var objCache = HttpRuntime.Cache;
    23. objCache.Insert(cacheKey, objObject);
    24. }
    25. /// <summary>
    26. /// 设置数据缓存
    27. /// </summary>
    28. public static void SetCache(string cacheKey, object objObject, int timeout = 7200)
    29. {
    30. try
    31. {
    32. if (objObject == null) return;
    33. var objCache = HttpRuntime.Cache;
    34. //相对过期
    35. //objCache.Insert(cacheKey, objObject, null, DateTime.MaxValue, timeout, CacheItemPriority.NotRemovable, null);
    36. //绝对过期时间
    37. objCache.Insert(cacheKey, objObject, null, DateTime.Now.AddSeconds(timeout), TimeSpan.Zero, CacheItemPriority.High, null);
    38. }
    39. catch (Exception)
    40. {
    41. //throw;
    42. }
    43. }
    44. /// <summary>
    45. /// 移除指定数据缓存
    46. /// </summary>
    47. public static void RemoveAllCache(string cacheKey)
    48. {
    49. var cache = HttpRuntime.Cache;
    50. cache.Remove(cacheKey);
    51. }
    52. /// <summary>
    53. /// 移除全部缓存
    54. /// </summary>
    55. public static void RemoveAllCache()
    56. {
    57. var cache = HttpRuntime.Cache;
    58. var cacheEnum = cache.GetEnumerator();
    59. while (cacheEnum.MoveNext())
    60. {
    61. cache.Remove(cacheEnum.Key.ToString());
    62. }
    63. }
    64. }