Transferred from: http://www.cnblogs.com/knowledgesea/archive/2012/06/20/2536603.html
First, the cache concept, the benefits of caching, type.
Cache is a space for the use of time technology, the popular point is to put the data you get in memory for a period of time, in this short time the server does not read the database, or the real data source, but read the data you stored in memory, here you will wonder how to set the data, can store what Like data, storage time settings, real data source data changes the server does not read the existence of bias? Don't worry, the following slowly will be said.
Caching benefits, caching is a Web site performance optimization is an indispensable data processing mechanism, he can effectively alleviate the database pressure, for example, the site click-through rate of 1 million per minute, if you do not use cached static pages, there is no ViewState case (viewstate will produce a large number of strings , the server interaction data is a kind of pressure, so the General page is to disable viewstate, using the cache), only the user click on the page, this page read a database, so that the pressure on the database can imagine, if we use the cache here, set the cache is valid for 1 minutes, This minute only, click 1 million times is the same as the click once, are read once the database, the data source is cached in memory.
The main types of caches in ASP: page caching, data source caching, and custom data caching. Three main kinds.
Second, data cache
public partial class WebForm1:System.Web.UI.Page { protected void Page_Load (object sender, EventArgs e) { c6/>// cache["Date"]= the data to be cached; Here is a simple declaration of the custom cache using string datastr = DateTime.Now.ToLongTimeString (); Response.Write ("First output time:" +datastr+ "</br>"); This reads the current time, and when the page refreshes, the time here changes. If (cache["date"] = = NULL)//Determine if there is a cache with a value of date { cache["date"] = Datastr; Response.Write ("The second output time is:" +cache["date"] + "The current time read here"); This reads the current time, and when the page refreshes, the time here changes. } else { Response.Write (cache["date"] + "Here is the time to read from the cache");//The time in the cache read here, when the page is refreshed, here the changes will not change over time. } } }
The above data cache does not set the cache expiration time, so the first output time is the current time (the Refresh page will change), the second output time will always be the first time cached (Refresh page unchanged).
Here we add some useful parameters (on the code) to the data cache.
protected void Page_Load (object sender, EventArgs e) {string ids= ""; Maticsoft.BLL.ScriptsBak BLL = new Maticsoft.BLL.ScriptsBak (); list<maticsoft.model.scriptsbak> list = new list<maticsoft.model.scriptsbak> (); List = BLL. GetAll (); for (int i = 0; i < list. Count; i++) {ids + = List[i]. Scriptid.tostring () + "--"; } ids = ids + "Finish"; The IDs here are used to read the ID value in the table from the database and then use the--link to a string if (cache["key"] = = null) {Cache.Insert ("key", IDS, NULL, DateTime.Now.AddSeconds (+), System.Web.Caching.Cache.NoSlidingExpiration); Here to cache the data, set the cache time//"key" for the cache key, IDs for cached values, NULL for cache dependencies, there is no cache dependency, so null, the following is a detailed description of cache dependencies//n Ull after the cache time is 40 seconds//The last parameter is the format of the set time, ASP. NET allows you to set an absolute expiration time or sliding expiration time, but cannot be used at the same time,//We set the absolute expiration time, that is, the cache data is 40 seconds after the page is not refreshed, and 40 seconds after the database is retrieved again. Response.Write ("Cache loaded as---"+ cache[" key "] +" </br> "); } else {Response.Write ("Cache loaded as---" + cache["key"] + "</br>"); } Response.Write ("Directly loaded as---" + ids + "</br>"); }
Data caching: Add time-consuming entries to an object cache collection and store them as key values. We can use Cache.Insert() methods to set the expiration, priority, dependencies, etc. of the cache.
Third, page cache
protected void Page_Load (object sender, EventArgs e) { string date = DateTime.Now.ToString (); Response.Write (date); }
<%@ page language= "C #" autoeventwireup= "true" codebehind= "WebForm1.aspx.cs" inherits= "cache. WebForm1 "%><%@ OutputCache duration=" "varybyparam=" None "%> <!---added on this code means, add this page cache for 10 seconds, within 10 seconds, The Refresh page will read the value of the cached page and no longer executes the Page_Load method. the Page_Load method is performed every 10 seconds--><! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<%@ OutputCache duration= "Ten" varybyparam= "none"%> this directive tag adds a cache to this page, Duration This parameter specifies that the page cache time is 10 seconds, VaryByParam This specifies the page parameter, which is, for example, a page http://www.cnblogs.com/knowledgesea/admin/EditPosts.aspx?postid= 2536603&update=1, then his parameter is PostID and update, if such page we can write the instruction label as <%@ OutputCache duration= "varybyparam=" PostID The update "%> parameter is separated from the parameter with a semicolon, so it's okay to cache each individual page, and he caches postid=2536603&update=1 or postid=1&update=. 2 and so on different parameters page all cache up. Here you can use a simple method, that is <%@ OutputCache duration= "" "varybyparam=" * "%>, cache all the current page under the different parameters of the page.
Asp. NET no longer executes the life cycle of the page and the associated code but directly uses the cached page, which is simply understood in my comments.
Iv. Control Caching
1.ObjectDataSource such a data source control, you can find the corresponding property in the property bar to set, the following I listed an example, set the startup cache, the cache time is 10 seconds, the time type is absolute time.
<asp:objectdatasource id= "ObjectDataSource1" runat= "Server" enablecaching= "True" cacheduration= "10" Cacheexpirationpolicy= "Absolute" ></asp:ObjectDataSource>
2. Controls that do not have cached properties are cached
protected void Page_Load (object sender, EventArgs e) { string date = DateTime.Now.ToString (); TextBox1.Text = date; }
<%@ page language= "C #" autoeventwireup= "true" codebehind= "WebForm1.aspx.cs" inherits= "cache. WebForm1 "%><%@ OutputCache duration=" "varybycontrol=" TextBox1 "%><!--VaryByControl parameters for the control to be cached id-- ><! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">The TextBox control here is cached, where the cache time is 10 seconds, that is, in 10 seconds, ASP. NET no longer executes the page's life cycle and related code, but instead uses the cached page directly.
V. Cache dependency (verbose: http://www.cnblogs.com/knowledgesea/p/3904929.html)
protected void Page_Load (object sender, EventArgs e) { string str = ""; if (cache["key"] = = null) { str = System.IO.File.ReadAllText (Server.MapPath ("TextFile1.txt")); Read the data in the TextFile1.txt file cachedependency dp = new CacheDependency (Server.MapPath ("TextFile1.txt"));//Establish cache dependency DP Cache.Insert ("Key", STR, DP); Response.Write (cache["key"]); If the contents of this file are TextFile1.txt, the data in the cache is read, and once the data in the TextFile1.txt file is changed, the data in the TextFile1.txt file is re-read } else { Response.Write (cache["key"]); } }
Cache dependencies make the cache dependent on other resources, and when a dependency changes, the cache entry entry is automatically removed from the cache. A cache dependency can be a file, directory, or key with other objects in the application's cache. If a file or directory changes, the cache expires.
Vi. setting up caching in configuration files
<system.web> <caching> <outputCacheSettings> <outputCacheProfiles> <addname= "Productitemcacheprofile" duration= "/> </outputcacheprofiles></" Outputcachesettings> </caching></system.web>
<%@ page language= "C #" autoeventwireup= "true" codebehind= "WebForm1.aspx.cs" inherits= "cache. WebForm1 "%><%@ OutputCache cacheprofile=" Productitemcacheprofile "varybyparam=" None "%><!-- Here the CacheProfile parameter and the configuration file are kept one to--><! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
This adds a page with a cache of 60 seconds to the page.
Vii. Cached Callback functions
protected void Page_Load (object sender, EventArgs e) {string str = ""; if (cache["key"] = = null) {str = System.IO.File.ReadAllText (Server.MapPath ("TextFile1.txt")); /Read the data in the TextFile1.txt file CacheDependency dp = new CacheDependency (Server.MapPath ("TextFile1.txt"));//Establish cache dependency D P Cache.Insert ("key", STR, DP, DateTime.Now.AddSeconds (), Cache.noslidingexpiration, Cacheitempriority.lo W, CacheItemRemovedCallback); CacheItemPriority This parameter is the priority of the cache he is divided into several levels, in order to prevent the cache from being filled by the system itself to remove the cache priority in order to abolish the cache, followed by the name of the callback function. Response.Write (cache["key"]); If the content of this file is TextFile1.txt, the data in the cache is read, and once the data in the TextFile1.txt file is changed, the data in the TextFile1.txt file is re-read} else {Response.Write (cache["key"]); }} public void CacheItemRemovedCallback (string key, object value, CacheItemRemovedReason reason)//This is for cache removal callback function, be sure to maintain the same name as the last parameter in the Cache.Insert () method, The delegate is used here, and you can see it in the Cache.Insert () function, so the format here can only be written in the way I wrote it. {System.IO.File.WriteAllText (Server.MapPath ("Log.txt"), "cache removal reason is:" +reason. ToString ()); }The callback function in the example writes the reason for generating a log.txt that the file records each time the cache is removed.
Viii. cache settings in a configuration file
Our server has the ability to turn on the cache, the cache function can reduce the time you visit the site when the site in the server compile times, greatly accelerate the speed of your site, if you need to update your site frequently, you can consider temporarily reduce the cache time, or temporarily shut down the cache
Please put the following code in the Web. config file in the root directory of your website;
1. In the Web. config, set the time to reduce the cache, in the Web. config, use the following definition
<system.webServer>
<caching>
<profiles>
<remove extension= ". aspx"/>
<add extension= ". aspx" policy= "Cachefortimeperiod"
Kernelcachepolicy= "DontCache" duration= "00:00:01" varybyquerystring= "*"/>
</profiles>
</caching>
</system.webServer>
2. If you want to turn off the caching feature of a page, use the following definition in Web. config
<configuration>
<location path= "showstockprice.asp" >
<system.webServer>
<caching>
<profiles>
<remove extension= ". asp"/>
<add extension= ". asp" policy= "DontCache" kernelcachepolicy= "DontCache"/>
</profiles>
</caching>
</system.webServer>
</location>
</configuration>
3. If you want to turn off the caching function for the entire program, use the following definition in Web. config
<configuration>
<system.webServer>
<caching>
<profiles>
<remove extension= ". asp"/>
<add extension= ". asp" policy= "DontCache" kernelcachepolicy= "DontCache"/>
</profiles>
</caching>
</system.webServer>
</configuration>
4. If you want to turn off the caching feature of one or several folders in the root directory, use the following definition in Web. config
<location path= "~/foldera,~/folderb" >
<system.webServer>
<caching>
<profiles>
<remove extension= ". asp"/>
<add extension= ". asp" policy= "DontCache" kernelcachepolicy= "DontCache"/>
</profiles>
</caching>
</system.webServer>
</location>
</configuration>
ASP. NET cache (RPM)