Asp. NET page Caching 4 Common ways _ Practical tips

Source: Internet
Author: User
Tags datetime md5 static class

This article has shared 4 kinds of common asp.net page caching way for everybody's reference, the concrete content is as follows

1, distributed cache memcached, tutorial Download

2, Memory cache, this occupies server resources

#region Memory Cache public class MemoryCache {#region write///<summary>///write data cache to memory///</summary>// /<remarks>tommyhu2011-7-28 10:25 Create </remarks>///<param name= "CacheKey" > Cache identification Keyword </param>/// <param name= "Cacheresult" > Data to be stored </param>///<param name= "cachetime" > Unit sec </param> Public static void Inertmemorycache (String CacheKey, Object cacheresult, int cachetime) {if (Cacheresult!= null) {Sys Tem. Web.HttpRuntime.Cache.Insert (CacheKey, Cacheresult, NULL, System.Web.Caching.Cache.NoAbsoluteExpiration, 
 Timespan.fromseconds (Cachetime)); #endregion #region Read///<summary>///read memory cache information based on cache identity///</summary>///<remarks>tomm yhu2011-7-28 10:25 Create </remarks>///<param name= "CacheKey" > Cache identity Keywords </param>///<returns> Memory cache data </returns> public static object Readmemorycache (String cachekey) {Object obj = system.web.httpruntime.c Ache. Get (cAchekey); 
 if (obj!= null) {return obj; 
 return null;  } #endregion} #endregion

3, XML cache , this is most common

 #region XML Cache public static class Xmlcache {private static string m_cachefoldername = null; #region get/Generate Cache file method (no cmdparams)///<summary>///get/Generate Cache file Method (DataTable)///</summary>///<param Name= SQL > Convert SQL to MD5 string </param>///<param name= "Cachefilepath" > The relative path of the XML file (the root directory has been preset) </param >///<param name= "CacheTime" > Cache time </param>///<param name= "dataused" > used database link string </param >///<returns></returns> public static DataTable cachefilebydatatable (String SQL, String Cachefilepath 
 , int CacheTime) {Sqlhelper.sqlhelper querysql = new Sqlhelper.sqlhelper (); if (Cachefilepath!= string. 
 Empty && Cachefilepath.startswith ("/")) {Cachefilepath = Cachefilepath.remove (0, 1); String SqlMd5 = sql;//used to convert SQL to MD5 string StrSqlByMd5 = System.Web.Security.FormsAuthentication.HashPasswordF 
 
 Orstoringinconfigfile (SqlMd5, "MD5");//generated MD5 filename string mycachefilepath = "";if (CacheTime >= 10000)//If more than 20 days the system defaults to persistent {Mycachefilepath = XMLCACHE.CACHEFOLDERNAMEP + cachefilepath;//for storing XML text Relative path} else {Mycachefilepath = xmlcache.cachefoldername + cachefilepath;//for storing XML file relative path} int Mycache Time = cachetime;//Cache times (sub) DataTable dt = new DataTable ()//DataTable DataTable with Data records Cachedt = new DataTable (); /Get a DataTable of cached data Records//attempt to get cached data records try {Cachedt = Datatablecache.getdtcache (Mycachetime, Mycachefilepath, STRs 
 QLBYMD5); 
 catch {Cachedt = null; 
 The IF (Cachedt!= null)//gets to the cached XML file {dt = Cachedt; 
  else//did not get the cached XML file {//Build DataTable (Query.processsql method if queried in query)//dt = Query.processsql (SqlMd5, dataused); 
 
  DT = QUERYSQL.RETDT (SQL); Save the DataTable as an XML file try {if (dt). DataSet!= null) {dt. 
  DataSet.Tables.Remove (DT); 
  } datatablecache.setdtcache (Mycachefilepath, StrSqlByMd5, DT); The catch (Exception ex) {//log.getcomlogger (). Error ("Save DataTable as XMLFile error: "+ ex." 
  message); 
 } return DT; ///<summary>///get/Generate Cache file Method (DataSet) Add by WJ 08-10-23///</summary>///<param name= "SQL" & gt; to convert SQL to MD5 string </param>///<param name= "Cachefilepath" > Store the relative path of the XML file (the root has been preset) </param>///< param name= "CacheTime" > Cache time </param>///<param name= "dbname" > used database link string </param>///< 
 returns></returns> public static DataSet Cachefilebydataset (String SQL, string cachefilepath, int CacheTime) 
 {Sqlhelper.sqlhelper querysql = new Sqlhelper.sqlhelper (); if (Cachefilepath!= string. 
 Empty && Cachefilepath.startswith ("/")) {Cachefilepath = Cachefilepath.remove (0, 1); String SqlMd5 = sql;//used to convert SQL to MD5 string StrSqlByMd5 = System.Web.Security.FormsAuthentication.HashPasswordF Orstoringinconfigfile (SqlMd5, "MD5")//generated MD5 filename string mycachefilepath = Xmlcache.cachefoldername + cachefilepath;// relative path int mycachetime = Cach for storing XML filesetime;//Cache Time (sub) DataSet ds = new DataSet ()///DataSet with data record cacheds = new DataSet ();//Get Cached data record dataset 
 Attempt to get cached data record try {cacheds = Datatablecache.getdscache (Mycachetime, Mycachefilepath, STRSQLBYMD5); 
 catch {cacheds = null; 
 } if (cacheds!= null)//gets to the cached XML file {ds = Cacheds; 
  else//failed to get cached XML file {//Generate DataSet//ds = Query.processmultisql (SqlMd5, dbname); 
 
  ds = Querysql.retds (SQL); 
  Save the dataset as an XML file try {Datatablecache.setdscache (Mycachefilepath, StrSqlByMd5, DS); 
 The catch {}} return DS; #endregion #region Get/Generate Cache file method (with Cmdparams)///<summary>///get/Generate Cache file Method (DataTable)///</summary >///<param name= "SQL" > is used to convert SQL to MD5 string </param>///<param name= "Cachefilepath" > Store the relative path of the XML file ( root directory preset) </param>///<param name= "CacheTime" > Cache time </param>///<param name= "dataused" > Link string for the database used </param>///<param name= "Cmdparams"To provide the parameter list </param>///<returns></returns> public static DataTable used in the SqlCommand command as an array 
 Cachefilebydatatable (String SQL, string cachefilepath, int CacheTime, string dbconstr, params sqlparameter[] cmdparams) 
 {Sqlhelper.sqlhelper querysql = new Sqlhelper.sqlhelper (); if (Cachefilepath!= string. 
 Empty && Cachefilepath.startswith ("/")) {Cachefilepath = Cachefilepath.remove (0, 1); 
 The string SqlMd5 = sql;//is used to convert SQL to MD5 string sqlmd5params = SQL; if (cmdparams!= null) {for (int i = 0; i < cmdparams.length; i++) {if (cmdparams[i). Value!= null) Sqlmd5params + = Cmdparams[i]. 
  Value.tostring (); } String StrSqlByMd5 = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile (Sqlmd5params, "M 
 
 D5 ");//generated MD5 filename string mycachefilepath =" "; if (CacheTime >= 10000)//If more than 20 days the system defaults to persistent {Mycachefilepath = XMLCACHE.CACHEFOLDERNAMEP + cachefilepath;//for storing XML text The relative path of the piece} else {MycachefiLepath = xmlcache.cachefoldername + cachefilepath;//The relative path for storing xml files int mycachetime = cachetime;//cache time (minutes) Datat Able dt = new DataTable ()//DataTable DataTable containing data records Cachedt = new DataTable ();//Get a DataTable of cached data Records//attempt to get cached data 
 
 Record Cachedt = Datatablecache.getdtcache (Mycachetime, Mycachefilepath, STRSQLBYMD5); 
 if (Cachedt!= null)//gets to the cached XML file {dt = Cachedt; 
  else//did not get the cached XML file {//Build DataTable (Query.processsql method if queried in query)//dt = Query.processsql (SqlMd5, dataused); 
  DT = QUERYSQL.RETDT (SQLMD5); 
  DataTable dt1 = new DataTable (); if (dt!= null) {dt1 = dt. 
  Copy (); 
 ///Save DataTable as XML file Datatablecache.setdtcache (Mycachefilepath, StrSqlByMd5, DT1); 
 } return DT; ///<summary>///get/Generate Cache file Method (DataSet) Add by WJF///</summary>///<param name= "SQL" > is used to SQL translates to MD5 string </param>///<param name= "Cachefilepath" > Store the relative path of the XML file (the root has been preset) </param>///<param Name= "CacheTime" > Cache time</param>///<param name= "dbname" > used database link string </param>///<param name= "Cmdparams" > Provides the parameter list </param>///<returns></returns> public static DataSet that is used in the SqlCommand command in the form of an array 
 Cachefilebydataset (String SQL, string cachefilepath, int CacheTime, string dbconstr, params sqlparameter[] cmdparams) { 
 Sqlhelper.sqlhelper querysql = new Sqlhelper.sqlhelper (); 
 String SqlMd5 = sql;//used to convert SQL to MD5 string sqlmd5params = SQL; if (cmdparams!= null) {for (int i = 0; i < cmdparams.length; i++) {if (cmdparams[i). Value!= null) Sqlmd5params + = Cmdparams[i]. 
  Value.tostring (); } String StrSqlByMd5 = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile (Sqlmd5params, "M D5 ");//generated MD5 filename string mycachefilepath = xmlcache.cachefoldername + cachefilepath;//the relative path int for storing XML files Mycachetim E = cachetime;//Cache Time (sub) DataSet ds = new DataSet ()//dataset DataSet with data record cacheds = new DataSet ()//Fetch cached dataRecorded dataset//attempt to get cached data records cacheds = Datatablecache.getdscache (Mycachetime, Mycachefilepath, STRSQLBYMD5); 
 if (cacheds!= null)//gets to the cached XML file {ds = Cacheds; 
  else//failed to get cached XML file {//Generate DataSet//ds = Query.processmultisql (SqlMd5, dbname); 
  ds = Querysql.retds (SQLMD5); 
  DataSet ds1 = new DataSet (); if (ds!= null) {DS1 = ds. 
  Copy (); 
 ///Save DataSet as XML file Datatablecache.setdscache (Mycachefilepath, StrSqlByMd5, DS1); 
 } return DS; #endregion #region non-persistent///<summary>///persisted///</summary> public static string Cachefold Ername {get {if (m_cachefoldername = = null)//if path {M_cachefoldername = System.configurati is not defined in Global.asax On. 
  ConfigurationManager.AppSettings.GetValues ("Cachepathroot") [0];  
  if (M_cachefoldername = null)//If the path is not defined in Web.config {return "/cachedata/" + DateTime.Now.ToString ("yyyyMMdd") + "/"; else {return m_cachefoldername + DateTime.Now.ToString ("yyyyMMdd") +"/"; 
  } else {return m_cachefoldername + DateTime.Now.ToString ("yyyyMMdd") + "/"; 
 } set {m_cachefoldername = value; } #endregion #region persisted (for example, data that holds Mapbar cache or needs to be updated for more than 3 months)///<summary>///persist (for example, storing Mapbar cached data or requiring 3 months to ///</summary> public static string Cachefoldernamep {get {if (M_cachefoldername = null)//AS The path {m_cachefoldername = System.Configuration.ConfigurationManager.AppSettings.GetValues ("global.asax") is not defined in the fruit 
  Cachepathroot ") [0]; 
  if (M_cachefoldername = null)//If the path is not defined in Web.config {return "/cachedata/"; 
  else {return m_cachefoldername; 
  } else {return m_cachefoldername; 
 } set {m_cachefoldername = value; 
 } #endregion} #endregion

4, DataTable Cache

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.