在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
关于缓存的设计 缓存是提高应用程序性能的最好方法之一。运用缓存可以优化数据查询,避免不必要的网络数据回传,和避免执行不必要的完全相同的数据处理逻辑。在实现缓存的时候我们要确定什么时候装入缓存数据。用异步装入缓存或用批处理方式来避免出现客户端数据延迟。
复制代码 代码如下: using System; using System.Collections; using System.Text.RegularExpressions; using System.Web; using System.Web.Caching; namespace Larry.Cache { /// <summary> /// 缓存类 Community Server的缓存类 /// </summary> public class BaseCache { /// <summary> /// CacheDependency 说明 /// 如果您向 Cache 中添加某个具有依赖项的项,当依赖项更改时, /// 该项将自动从 Cache 中删除。例如,假设您向 Cache 中添加某项, /// 并使其依赖于文件名数组。当该数组中的某个文件更改时, /// 与该数组关联的项将从缓存中删除。 /// [C#] /// Insert the cache item. /// CacheDependency dep = new CacheDependency(fileName, dt); /// cache.Insert("key", "value", dep); /// </summary> public static readonly int DayFactor = ; public static readonly int HourFactor = ; public static readonly int MinuteFactor = ; public static readonly double SecondFactor = 0.; private static readonly System.Web.Caching.Cache _cache; private static int Factor = ; /// <summary> /// 单件模式 /// </summary> static BaseCache() { HttpContext context = HttpContext.Current; if (context != null) { _cache = context.Cache; } else { _cache = HttpRuntime.Cache; } } /// <summary> /// 一次性清除所有缓存 /// </summary> public static void Clear() { IDictionaryEnumerator CacheEnum = _cache.GetEnumerator(); ArrayList al = new ArrayList(); while (CacheEnum.MoveNext()) //逐个清除 { al.Add(CacheEnum.Key); } foreach (string key in al) { _cache.Remove(key); } } public static void RemoveByPattern(string pattern) { IDictionaryEnumerator CacheEnum = _cache.GetEnumerator(); Regex regex = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Compiled); while (CacheEnum.MoveNext()) { if (regex.IsMatch(CacheEnum.Key.ToString())) _cache.Remove(CacheEnum.Key.ToString()); } } /// <summary> /// 清除特定的缓存 /// </summary> /// <param name="key"></param> public static void Remove(string key) { _cache.Remove(key); } /// <summary> /// 缓存OBJECT. /// </summary> /// <param name="key"></param> /// <param name="obj"></param> public static void Insert(string key, object obj) { Insert(key, obj, null, ); } /// <summary> /// <summary> /// <summary> /// <summary> /// <summary> }
/// <summary> /// <summary> /// <summary> public static void Permanent(string key, object obj, CacheDependency dep) public static object Get(string key) /// <summary> 其实这个类就是一个单件模式的设计 和缓存的公共操作方法,其中CacheDependency表示建立缓存依赖项,CacheItemPriority表示缓存的优先级。S使用如下 复制代码 代码如下: public static CardShop.Model.Systems GetConfig() { const string cacheKey = "WebConfig"; CardShop.Model.Systems sampleCacheTable = Larry.Cache.BaseCache.Get(cacheKey) as CardShop.Model.Systems; if (sampleCacheTable == null) { OprationCheck.Message("第一次加载使用缓存"); sampleCacheTable = model; Larry.Cache.BaseCache.Insert(cacheKey, sampleCacheTable, 24 * Larry.Cache.BaseCache.MinuteFactor); } else { OprationCheck.Message("已经加载了缓存不需要再加载"); } return sampleCacheTable; } |
请发表评论