通常我们针对页面以及相关数据进行相应的缓存(分为客户端和服务端的缓存),以下代码为对一般操作 进行相应的缓存(服务端),用以减少对数据库的访问次数,减少服务器的压力。
(一)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进行相应的操作。
以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索insert
, string
, static
, dependencies
, key
, public
, list removeall
Dependency
cache缓存服务器、cachehelper、c cachehelper、java cachehelper、c cache helper,以便于您获取更多的相关知识。