Welcome 微信登录

首页 / 网页编程 / ASP.NET / CacheHelper对缓存的控制 减轻服务器的压力

CacheHelper对缓存的控制 减轻服务器的压力2013-11-28 博客园 JasenKin通常我们针对页面以及相关数据进行相应的缓存(分为客户端和服务端的缓存),以下代码为对一般操作 进行相应的缓存(服务端),用以减少对数据库的访问次数,减少服务器的压力。

(一)CacheHelper 类

CacheHelper类主要是依赖于系统的System.Web.Caching.HostingEnvironment.Cache,具体代码如 下:

public static class CacheHelper{private static Cache _cache;public static double SaveTime { get; set;}static CacheHelper(){_cache = HostingEnvironment.Cache;SaveTime = 15.0;}public static object Get(string key){if (string.IsNullOrEmpty(key)){return null;}return _cache.Get(key);}public static T Get<T>(string key){object obj = Get(key);return obj==null?default(T):(T)obj;}public static void Insert(string key, object value, CacheDependency dependency, CacheItemPriority priority, CacheItemRemovedCallback callback){_cache.Insert(key, value, dependency, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(SaveTime), priority, callback);}public static void Insert(string key, object value, CacheDependency dependency, CacheItemRemovedCallback callback){Insert(key, value, dependency, CacheItemPriority.Default, callback);}public static void Insert(string key, object value, CacheDependency dependency){Insert(key, value, dependency, CacheItemPriority.Default, null);}public static void Insert(string key, object value){Insert(key, value, null, CacheItemPriority.Default, null);}public static void Remove(string key){if (string.IsNullOrEmpty(key)){return;}_cache.Remove(key);}public static IList<string> GetKeys(){List<string> keys = new List<string>();IDictionaryEnumerator enumerator = _cache.GetEnumerator();while (enumerator.MoveNext()){keys.Add(enumerator.Key.ToString());}return keys.AsReadOnly();}public static void RemoveAll(){IList<string> keys = GetKeys();foreach (string key in keys){_cache.Remove(key);}}}}
在原有基础上增加了如下3个方法:

(1)public static T Get<T>(string key)

(2)public static IList<string> GetKeys()

(3)public static void RemoveAll ()
 

这样我们能够方便的以静态方法来对Cache进行相应的操作。