Cache缓存帮助类

public class Cache
{
    private static Cache _cache = HttpRuntime.Cache;
    /// <summary>
    /// 本地缓存获取
    /// </summary>
    /// <param name="name">key</param>
    /// <returns></returns>
    public static object GetCache(string name)
    {
        return Cache._cache.Get(name);
    }
    /// <summary>
    /// 本地缓存写入(默认缓存20min)
    /// </summary>
    /// <param name="name">key</param>
    /// <param name="value">value</param>
    public static void SetCache(string name, object value)
    {
        Cache._cache.Insert(name, value, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(20.0));
    }
    /// <summary>
    /// 本地缓存写入
    /// </summary>
    /// <param name="name">key</param>
    /// <param name="value">value</param>
    /// <param name="minutes">缓存分钟</param>
    public static void SetCache(string name, object value, int minutes)
    {
        Cache._cache.Insert(name, value, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes((double)minutes));
    }
    /// <summary>
    /// 读取缓存
    /// </summary>
    /// <param name="cacheKey"></param>
    /// <returns></returns>
    public static T GetCache<T>(string cacheKey) where T : class
    {
        bool flag = Cache._cache[cacheKey] != null;
        T result;
        if (flag)
        {
            result = (T)Cache._cache[cacheKey];
        }
        else
        {
            result = default(T);
        }
        return result;
    }
    /// <summary>
    /// 写入缓存
    /// </summary>
    /// <param name="value">对象数据</param>
    /// <param name="cacheKey"></param>
    public static void SetCache<T>(T value, string cacheKey) where T : class
    {
        Cache._cache.Insert(cacheKey, value, null, DateTime.Now.AddMinutes(20.0), Cache.NoSlidingExpiration);
    }
    /// <summary>
    /// 写入缓存
    /// </summary>
    /// <param name="value">对象数据</param>
    /// <param name="cacheKey"></param>
    /// <param name="expireTime">到期时间</param>
    public static void SetCache<T>(T value, string cacheKey, DateTime expireTime) where T : class
    {
        Cache._cache.Insert(cacheKey, value, null, expireTime, Cache.NoSlidingExpiration);
    }
    /// <summary>
    /// 移除指定数据缓存
    /// </summary>
    /// <param name="cacheKey"></param>
    public static void RemoveCache(string cacheKey)
    {
        Cache._cache.Remove(cacheKey);
    }
    /// <summary>
    /// 移除全部缓存
    /// </summary>
    public static void RemoveCache()
    {
        IDictionaryEnumerator enumerator = Cache._cache.GetEnumerator();
        while (enumerator.MoveNext())
        {
            Cache._cache.Remove(enumerator.Key.ToString());
        }
    }
}

 

posted @ 2022-09-29 19:38  每天进步多一点  阅读(31)  评论(0编辑  收藏  举报