CacheHelper

using System;
using System.Web;
using System.Web.Caching;

namespace Common
{
    /// <summary>
    /// 缓存辅助类
    /// </summary>
    public static class CacheHelper
    {
        /// <summary>
        /// 根据键获取缓存数据
        /// </summary>
        /// <param name="cacheKey"></param>
        /// <returns></returns>
        public static object GetCache(string cacheKey)
        {
            var objCache = HttpRuntime.Cache;
            return objCache.Get(cacheKey);
        }

        /// <summary>
        ///  设置缓存
        /// </summary>
        /// <param name="cacheKey">缓存键</param>
        /// <param name="objValue">缓存键</param>
        public static void SetCache(string cacheKey, object objValue)
        {
            var cache = HttpRuntime.Cache;
            cache.Insert(cacheKey, objValue);
        }

        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <param name="cacheKey">缓存键</param>
        /// <param name="objValue">缓存的值</param>
        /// <param name="timeout">过期时间</param>
        public static void SetCache(string cacheKey, object objValue, TimeSpan timeout)
        {
            var cache = HttpRuntime.Cache;
            cache.Insert(cacheKey, objValue, null, DateTime.MaxValue, timeout, CacheItemPriority.NotRemovable, null);
        }

        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <param name="cacheKey">缓存键</param>
        /// <param name="objValue">缓存的value</param>
        /// <param name="absoluteExpiration">绝对过期时间</param>
        /// <param name="slidingExpiration">滑动过期时间</param>
        public static void SetCache(string cacheKey, object objValue, DateTime absoluteExpiration, TimeSpan slidingExpiration)
        {
            var cache = HttpRuntime.Cache;
            cache.Insert(cacheKey, objValue, null, absoluteExpiration, slidingExpiration);
        }

        /// <summary>
        /// 移除指定的缓存
        /// </summary>
        /// <param name="cacheKey"></param>
        public static void RemoveCache(string cacheKey)
        {
            var cache = HttpRuntime.Cache;
            cache.Remove(cacheKey);
        }

        /// <summary>
        /// 移除全部缓存
        /// </summary>
        public static void RemoveAllCache()
        {
            var cache = HttpRuntime.Cache;
            var cacheEnum = cache.GetEnumerator();
            while (cacheEnum.MoveNext())
            {
                if (cacheEnum.Key != null) cache.Remove(cacheEnum.Key.ToString());
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值