[Switch] ASP.NET cache usage

This article is reproduced from: https://blog.csdn.net/mss359681091/article/details/51076712

Introduction to this article: Cache objects are often used in .NET applications. There are HttpContext.Current.Cache and HttpRuntime.Cache, HttpRuntime.Cache is application level, and HttpContext.Current.Cache is defined for the current WEB context. In addition to being used in WEB under HttpRuntime, non-WEB programs can also be used.
 

1. HttpRuntime.Cache is equivalent to a specific implementation class of cache, although this class is placed under the System.Web namespace. But non-Web applications can also be used.


2. HttpContext.Cache is the encapsulation of the above cache classes. Since it is encapsulated into HttpContext, it can only be used when HttpContext is known, that is, it can only be used in Web applications.

To sum up, if possible, try to use HttpRuntime.Cache instead of HttpContext.Cache.

 

1. There are the following rules for caching data


First, data may be used frequently, and this data can be cached.


Second, the access frequency of data is very high, or the access frequency of a data is not high, but its life cycle is very long, such data is best cached.


The third is a problem that is often overlooked. Sometimes we cache too much data. Usually on an X86 machine, if the data you want to cache exceeds 800M, there will be a memory overflow error. So the cache is limited. In other words, you should estimate the size of the cache set and limit the size of the cache set to less than 10, otherwise it may go wrong. In Asp.net, if the cache is too large, an out-of-memory error will also be reported, especially if the cache is large DataSet objects.

You should analyze your program carefully. Depending on the actual situation, see where to use it and where not to use it. For example, excessive use of the cache will also increase the pressure on the server. The full page output cache will affect the update of data. If you really need to cache a large amount of data, you can consider static techniques.

 

Second, the following introduces the common methods of HttpRuntime.Cache

 

C# code 
[csharp]  view plain copy  
 
  1. <strong>using System;  
  2. using System.Web;  
  3. using System.Collections;  
  4.   
  5. public class CookiesHelper  
  6.     {  
  7.     /**//// <summary>  
  8.     /// Get the data cache  
  9.     /// </summary>  
  10.     /// <param name="CacheKey">键</param>  
  11.     public static object GetCache(string CacheKey)  
  12.     {  
  13.         System.Web.Caching.Cache objCache = HttpRuntime.Cache;  
  14.         return objCache[CacheKey];  
  15.     }  
  16.   
  17.     /**//// <summary>  
  18.     /// Set up the data cache  
  19.     /// </summary>  
  20.     public static void SetCache(string CacheKey, object objObject)  
  21.     {  
  22.         System.Web.Caching.Cache objCache = HttpRuntime.Cache;  
  23.         objCache.Insert(CacheKey, objObject);  
  24.     }  
  25.   
  26.     /**//// <summary>  
  27.     /// Set up the data cache  
  28.     /// </summary>  
  29.     public static void SetCache(string CacheKey, object objObject, TimeSpan Timeout)  
  30.     {  
  31.         System.Web.Caching.Cache objCache = HttpRuntime.Cache;  
  32.         objCache.Insert(CacheKey, objObject, null, DateTime.MaxValue, Timeout, System.Web.Caching.CacheItemPriority.NotRemovable, null);  
  33.     }  
  34.   
  35.     /**//// <summary>  
  36.     /// Set up the data cache  
  37.     /// </summary>  
  38.     public static void SetCache(string CacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration)  
  39.     {  
  40.         System.Web.Caching.Cache objCache = HttpRuntime.Cache;  
  41.         objCache.Insert(CacheKey, objObject, null, absoluteExpiration, slidingExpiration);  
  42.     }  
  43.   
  44.     /**//// <summary>  
  45.     /// Remove the specified data cache  
  46.     /// </summary>  
  47.     public static void RemoveAllCache(string CacheKey)  
  48.     {  
  49.         System.Web.Caching.Cache _cache = HttpRuntime.Cache;  
  50.         _cache.Remove(CacheKey);  
  51.     }  
  52.   
  53.     /**//// <summary>  
  54.     /// Remove all caches  
  55.     /// </summary>  
  56.     public static void RemoveAllCache()  
  57.     {  
  58.         System.Web.Caching.Cache _cache = HttpRuntime.Cache;  
  59.         IDictionaryEnumerator CacheEnum = _cache.GetEnumerator();  
  60.         while (CacheEnum.MoveNext())  
  61.         ...{  
  62.             _cache.Remove(CacheEnum.Key.ToString());  
  63.         }  
  64.     }  
  65. }  
  66. </strong>  
3. Actual combat, personal projects
1. The first step is to join in global.asax
[html]  view plain copy  
 
  1. <strong>    void Application_Start(object sender, EventArgs e)  
  2.     {  
  3.         // code to run when the application starts  
  4.         try  
  5.         {  
  6.             //define the connection string  
  7.             string conStr = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;  
  8.             System.Data.SqlClient.SqlDependency.Start(conStr);//Start the listening service, ps: just start it once  
  9.             System.Web.Caching.SqlCacheDependencyAdmin.EnableNotifications(conStr);//Set the database connection for notification, ps: only need to set it once  
  10.             string[] str = { "TMS_OptionScoreDetails", "TMS_TeachAssess", "TMS_TeachAssessDetail", "TMS_TeachAssessPublish", "TMS_TeachAssessRecord", "TMS_TeachAssessRecordDetails", "TMS_TeachOption" };  
  11.             System.Web.Caching.SqlCacheDependencyAdmin.EnableTableForNotifications(conStr, str);//Set the database connection and table for notification, ps: only need to set it once  
  12.   
  13.   
  14.         }  
  15.         catch  
  16.         {  
  17.   
  18.         }  
  19.     }  
  20. </strong>  
2. The second step is to reference the cache class and use it in the project.
[csharp]  view plain copy  
 
  1. //cache  
  2.   DataSet myDataSet = new DataSet();  
  3.   
  4.   string CacheKey = "SearchDate" + TeachAssessID;  
  5.   object objModel = TMSCommonMethod.GetCache(CacheKey); //Get from the cache  
  6.   if (objModel ==  null) //nothing in the cache  
  7.   {  
  8.       TMSTeachAssessDetailManager myTMSTeachAssessDetailManager = new TMSTeachAssessDetailManager();  
  9.       TMSTeachAssessDetailQuery myTMSTeachAssessDetailQuery = new TMSTeachAssessDetailQuery();  
  10.       //myTMSTeachAssessDetailQuery.TeachAssessPublishID = TeachAssessPublishID;  
  11.       myTMSTeachAssessDetailQuery.TeachAssessID = TeachAssessID;  
  12.       myDataSet = myTMSTeachAssessDetailManager.SearchDate(null, myTMSTeachAssessDetailQuery);  
  13.   
  14.       objModel = myDataSet; // store the data in the cache  
  15.       if (objModel != null)  
  16.       {  
  17.             
  18.           System.Web.Caching.SqlCacheDependency dep = new System.Web.Caching.SqlCacheDependency(ConfigurationManager.AppSettings["CacheDataBaseName"].ToString(), TMSTeachAssessDetail.TABLENAME);  
  19.           TMSCommonMethod.SetCache(CacheKey, objModel, dep); //Write to cache  
  20.       }  
  21.   }  
  22.   else  
  23.   {  
  24.       myDataSet = (DataSet)objModel;  
  25.   }  


 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325078507&siteId=291194637