写在前面
在项目中的统计模块中,查询耗费的时间,实在是太长了,通过优化sql语句或者添加缓存来提高查询的速度,自己就弄了一个缓存的辅助类,方便操作缓存中的数据。
CacheHelper
1 using System; 2 using System.Collections; 3 using System.Collections.Generic; 4 using System.Linq; 5 using System.Text; 6 using System.Threading.Tasks; 7 using System.Web; 8 using System.Web.Caching; 9 namespace WebSite.Statistics.Core.Utilities10 {11 ///12 /// 缓存辅助类13 /// 14 public static class CacheHelper15 {16 ///17 /// 根据键获取缓存数据18 /// 19 /// 20 ///21 public static object GetCache(string cacheKey)22 {23 Cache objCache = HttpRuntime.Cache;24 return objCache.Get(cacheKey);25 }26 /// 27 /// 设置缓存28 /// 29 /// 缓存键30 /// 缓存键31 public static void SetCache(string cacheKey, object objValue)32 {33 Cache cache = HttpRuntime.Cache;34 cache.Insert(cacheKey, objValue);35 }36 ///37 /// 设置缓存38 /// 39 /// 缓存键40 /// 缓存的值41 /// 过期时间42 public static void SetCache(string cacheKey, object objValue, TimeSpan timeout)43 {44 Cache cache = HttpRuntime.Cache;45 cache.Insert(cacheKey, objValue, null, DateTime.MaxValue, timeout, System.Web.Caching.CacheItemPriority.NotRemovable, null);46 }47 ///48 /// 设置缓存49 /// 50 /// 缓存键51 /// 缓存的value52 /// 绝对过期时间53 /// 滑动过期时间54 public static void SetCache(string cacheKey, object objValue, DateTime absoluteExpiration, TimeSpan slidingExpiration)55 {56 Cache cache = HttpRuntime.Cache;57 cache.Insert(cacheKey, objValue, null, absoluteExpiration, slidingExpiration);58 }59 ///60 /// 移除指定的缓存61 /// 62 /// 63 public static void RemoveCache(string cacheKey)64 {65 System.Web.Caching.Cache cache = HttpRuntime.Cache;66 cache.Remove(cacheKey);67 }68 ///69 /// 移除全部缓存70 /// 71 public static void RemoveAllCache()72 {73 System.Web.Caching.Cache cache = HttpRuntime.Cache;74 IDictionaryEnumerator CacheEnum = cache.GetEnumerator();75 while (CacheEnum.MoveNext())76 {77 cache.Remove(CacheEnum.Key.ToString());78 }79 }80 }81 }
总结
缓存用到的地方很多,封装的这个类,也算很基础的东西了,算是记录一下,以后用到的时候,方便查找。