Instructions for using the.NET cache design

  • 2020-05-30 19:46:55
  • OfStack

The design of the cache
1. When do you use caching

Caching is one of the best ways to improve application performance. Caching can be used to optimize data queries, to avoid unnecessary network data backpassing, and to avoid performing exactly the same data processing logic that is not necessary. When implementing the cache we need to determine when to load the cache data. Avoid client data latency by loading the cache asynchronously or by batching.
Generally speaking, if the same business logic is requested in 1 certain period of time without change, it can be designed with caching. Requests with frequent data requests are not suitable for caching, such as forum replies, but forum topics can be designed with caching.


2. Steps of cache design
Determine the cache data structure: that is, what data is used by the cache in the design, and design the cache structure for that data
Determine what data to cache
Determine cache expiration rules and cleanup
Determine how to load the cached data


3. Example Community Server's cache class



using System;
  using System.Collections;
  using System.Text.RegularExpressions;
  using System.Web;
  using System.Web.Caching;

  namespace Larry.Cache
  {
      /// <summary>
     ///  The cache class  Community Server The cache class 
     /// </summary>
     public class BaseCache
     {
         /// <summary>
         /// CacheDependency  instructions 
         ///  If you are to  Cache  To add an item with a dependency. When the dependency changes, 
         ///  The item will automatically follow  Cache  Removed. For example, suppose you want to  Cache  To add an item to, 
         ///  And make it dependent on an array of file names. When a file in the array changes, 
         ///  Items associated with this array are removed from the 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>
         ///  A singleton 
         /// </summary>
         static BaseCache()
         {
             HttpContext context = HttpContext.Current;
             if (context != null)
             {
                 _cache = context.Cache;
             }
             else
             {
                 _cache = HttpRuntime.Cache;
             }
         }

         /// <summary>
         /// 1 Secondary clearing of all caches 
         /// </summary>
         public static void Clear()
         {
             IDictionaryEnumerator CacheEnum = _cache.GetEnumerator();
             ArrayList al = new ArrayList();
             while (CacheEnum.MoveNext()) // One by one to clear 
             {
                 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>
         ///  Clear the specific cache 
         /// </summary>
         /// <param name="key"></param>
         public static void Remove(string key)
         {
             _cache.Remove(key);
         }

         /// <summary>
         ///  The cache OBJECT. 
         /// </summary>
         /// <param name="key"></param>
         /// <param name="obj"></param>
         public static void Insert(string key, object obj)
         {
             Insert(key, obj, null, );
         }
        /// <summary>
        ///  The cache obj  And establish dependencies 
        /// </summary>
        /// <param name="key"></param>
        /// <param name="obj"></param>
        /// <param name="dep"></param>
        public static void Insert(string key, object obj, CacheDependency dep)
        {
            Insert(key, obj, dep, MinuteFactor * );
        }
        /// <summary>
        ///  Cache objects by seconds 
        /// </summary>
        /// <param name="key"></param>
        /// <param name="obj"></param>
        /// <param name="seconds"></param>
        public static void Insert(string key, object obj, int seconds)
        {
            Insert(key, obj, null, seconds);
        }
        /// <summary>
        ///  Cache objects by seconds   And store the priority 
        /// </summary>
        /// <param name="key"></param>
        /// <param name="obj"></param>
        /// <param name="seconds"></param>
        /// <param name="priority"></param>
        public static void Insert(string key, object obj, int seconds, CacheItemPriority priority)
        {
            Insert(key, obj, null, seconds, priority);
        }
        /// <summary>
        ///  Cache objects by seconds   And establish dependencies 
        /// </summary>
        /// <param name="key"></param>
        /// <param name="obj"></param>
        /// <param name="dep"></param>
        /// <param name="seconds"></param>
        public static void Insert(string key, object obj, CacheDependency dep, int seconds)
        {
            Insert(key, obj, dep, seconds, CacheItemPriority.Normal);
        }
        /// <summary>
        ///  Cache objects by seconds   And establish dependencies that have a priority 
        /// </summary>
        /// <param name="key"></param>
        /// <param name="obj"></param>
        /// <param name="dep"></param>
        /// <param name="seconds"></param>
        /// <param name="priority"></param>
        public static void Insert(string key, object obj, CacheDependency dep, int seconds, CacheItemPriority priority)
        {
            if (obj != null)
            {
                _cache.Insert(key, obj, dep, DateTime.Now.AddSeconds(Factor * seconds), TimeSpan.Zero, priority, null);
            }
        }

        public static void MicroInsert(string key, object obj, int secondFactor)
        {
            if (obj != null)
            {
                _cache.Insert(key, obj, null, DateTime.Now.AddSeconds(Factor * secondFactor), TimeSpan.Zero);
            }
        }
        /// <summary>
        ///  Maximum time cache 
        /// </summary>
        /// <param name="key"></param>
        /// <param name="obj"></param>
        public static void Max(string key, object obj)
        {
            Max(key, obj, null);
        }
        /// <summary>
        ///  Maximum time cache with dependencies 
        /// </summary>
        /// <param name="key"></param>
        /// <param name="obj"></param>
        /// <param name="dep"></param>
        public static void Max(string key, object obj, CacheDependency dep)
        {
            if (obj != null)
            {
                _cache.Insert(key, obj, dep, DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.AboveNormal, null);
            }
        }
        /// <summary>
        /// Insert an item into the cache for the Maximum allowed time
        /// </summary>
        /// <param name="key"></param>
        /// <param name="obj"></param>
        public static void Permanent(string key, object obj)
        {
            Permanent(key, obj, null);
        }
        public static void Permanent(string key, object obj, CacheDependency dep)
        {
            if (obj != null)
            {
                _cache.Insert(key, obj, dep, DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.NotRemovable, null);
            }
        }
        public static object Get(string key)
        {
            return _cache[key];
        }
        /// <summary>
        /// Return int of seconds * SecondFactor
        /// </summary>
        public static int SecondFactorCalculate(int seconds)
        {
            // Insert method below takes integer seconds, so we have to round any fractional values
            return Convert.ToInt(Math.Round((double)seconds * SecondFactor));
        }
    }
}

In fact, this class is the design of a singleton pattern and the common operation method of cache, where CacheDependency stands for the establishment of cache dependencies and CacheItemPriority stands for the priority of cache. S is used as follows


 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(" The first 1 The secondary load USES the cache ");
             sampleCacheTable = model;
             Larry.Cache.BaseCache.Insert(cacheKey, sampleCacheTable, 24 * Larry.Cache.BaseCache.MinuteFactor);
        }
        else
        {
            OprationCheck.Message(" The cache has already been loaded and does not need to be loaded again ");
        }
        return sampleCacheTable;
    }


Related articles: