C#中对缓存操作的封装类

这两天在开发过程中用到了C#中的数据缓存的一些操作,例如写入,读取,删除这些基本的操作。

然后就顺便去度娘看了下关于数据缓存的一些内容,发现缓存用好了还是蛮牛逼的,然后就顺手封装了一个缓存操作的类,方便你我他。

封装类代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Caching;

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

        /// <summary>
        /// 设置数据缓存
        /// </summary>
        /// <param name="cacheKey">键</param>
        /// <param name="objObject">值</param>
        public static void SetCache(string cacheKey, object objObject)
        {
            var objCache = HttpRuntime.Cache;
            objCache.Insert(cacheKey, objObject);
        }
        
        /// <summary>
        /// 设置数据缓存
        /// </summary>
        /// <param name="cacheKey">键</param>
        /// <param name="objObject">值</param>
        /// <param name="timeout">缓存时间</param>
        public static void SetCache(string cacheKey, object objObject, int timeout = 7200)
        {
            try
            {
                if (objObject == null) return;
                var objCache = HttpRuntime.Cache;
                //相对过期时间
                //objCache.Insert(cacheKey, objObject, null, DateTime.MaxValue, timeout, CacheItemPriority.NotRemovable, null);  
                DateTime dateTime = DateTime.Now.AddSeconds(timeout);
                //绝对过期时间  
                objCache.Insert(cacheKey, objObject, null, DateTime.Now.AddSeconds(timeout), TimeSpan.Zero, CacheItemPriority.High, null);
            }
            catch (Exception)
            {
                //throw;  
            }
        }
        
        /// <summary>
        /// 移除指定缓存
        /// </summary>
        /// <param name="cacheKey">键</param>
        public static void RemoveAllCache(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())
            {
                cache.Remove(cacheEnum.Key.ToString());
            }
        }
    }
}

具体的用法(写入的是什么类型就用什么类型接收就可以了 ) :

//写操作
CacheHelper.SetCache("key", value, 300);
//读操作
CacheHelper.GetCache("key");
//删操作
CacheHelper.RemoveAllCache("key");
CacheHelper.RemoveAllCache()

本案例结束。

THE END