using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; namespace Common { /// <summary> /// 封装对缓存的操作!(对缓存的操作,最重要的就是取和存) /// </summary> public class CacheHelper { /// <summary> /// 根据缓存的key,从缓存中取数据。 /// </summary> /// <param name="key"></param> /// <returns></returns> public static object Get(string key) { System.Web.Caching.Cache cache = HttpRuntime.Cache; return cache[key]; } /// <summary> /// 向缓存中,添加数据。 /// </summary> /// <param name="key">缓存中的key</param> /// <param name="value">缓存的数据value</param> public static void Set(string key, object value) { System.Web.Caching.Cache cache = HttpRuntime.Cache; cache[key] = value; } /// <summary> /// 向缓存中添加数据,并且设置绝对过期时间 /// </summary> /// <param name="key">缓存中的key</param> /// <param name="value">缓存的数据value</param> /// <param name="time">绝对过期时间</param> public static void Set(string key, object value, DateTime time) { System.Web.Caching.Cache cache = HttpRuntime.Cache; cache.Insert(key, value, null, time, TimeSpan.Zero); } /// <summary> /// 向缓存中添加数据,并且设置滑动过期时间 /// </summary> /// <param name="key">缓存中的key</param> /// <param name="value">缓存的数据value</param> /// <param name="timeSpan">滑动过期时间(分钟)</param> public static void Set(string key, object value, int timeSpan) { System.Web.Caching.Cache cache = HttpRuntime.Cache; cache.Insert(key, value, null, DateTime.MaxValue, new TimeSpan(0, timeSpan, 0)); } /// <summary> /// 移除缓存中的数据 /// </summary> /// <param name="key"></param> public static void Remove(string key) { System.Web.Caching.Cache cache = HttpRuntime.Cache; cache.Remove(key); } } }