Caching concepts, caching benefits, and types.
--------------------------------------------------------------------------------caching is a technology that uses space for time, which means that the data you get stored in memory for some time, in this short time the server does not read the database, or real data source, but read your stored in memory data, here you will be puzzled how to set up the data, what kind of data can be stored, storage time settings, the real data source data Change server does not read the existence of deviations? Don't worry, the following will be said slowly.
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 per minute 1 million clicks, if not using the cached static page, there is no ViewState case (viewstate will produce a lot 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 clicks on the page, the page read a database, so that the pressure on the database can be imagined, if we use the cache, set the cache is valid for 1 minutes, Then this minute only, click 1 million times and click once is the same, are read a database, the data source is cached in memory.
The cache in ASP.net is mainly divided into three main types: page caching, data source caching, and custom data caching.
--------------------------------------------------------------------------------
Second, data caching
--------------------------------------------------------------------------------
Copy Code code as follows:
public partial class WebForm1:System.Web.UI.Page
{
protected void Page_Load (object sender, EventArgs e)
{
cache["Date"]= the data to be cached; Here is a simple declaration using a custom cache
String datastr = DateTime.Now.ToLongTimeString ();
Response.Write ("First output time:" +datastr+ "</br>"); Read here the current time, refresh the page when the time here will change with.
if (cache["date"] = = null)//To determine whether a cache exists that has a value of date
{
cache["date"] = Datastr;
Response.Write ("The second output time is:" +cache["date"] + "The current time read here"); Read here the current time, refresh the page when the time here will change with.
}
Else
{
Response.Write (cache["date"] + "Here is the time read from cache");//The time in the cache read here, when refreshing the page, the changes here will not change over time.
}
}
}
The above data cache because the cache expiration is not set, the first output time is the current time (the Refresh page changes), and the second output time is the first time cached (the Refresh page is unchanged).
Here we add some useful parameters to the data cache (code above).
--------------------------------------------------------------------------------
Copy Code code as follows:
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 + "End"; The IDs here is a string that reads the ID values from the database and then uses--linked
if (cache["key"] = = null)
{
Cache.Insert ("Key", IDs, NULL, DateTime.Now.AddSeconds (), System.Web.Caching.Cache.NoSlidingExpiration); Caching the data here, setting the cache time
"Key" is a cached key, IDS is cached, NULL is a cache dependency, no cache dependencies are used here, and so is null, and the cache dependencies are described below in detail
Null followed by 40 seconds of cache time
The last parameter is the format of the set time, ASP. NET allows you to set an absolute expiration or sliding expiration time, but not at the same time,
We set the absolute expiration here, that is, the cached data is 40 seconds after the page is not refreshed, and will be retrieved from the database after 40 seconds.
Response.Write ("Cache Load for---" + cache["key"] + "</br>");
}
Else
{
Response.Write ("Cache Load for---" + cache["key"] + "</br>");
}
Response.Write ("Directly loaded as---" + ids + "</br>");
}
Data caching: Add some time-consuming entries to an object cache collection and store them as key values. We can set the cache expiration, priority, dependencies, and so on by using the Cache.Insert () method.
--------------------------------------------------------------------------------
Third, page caching
--------------------------------------------------------------------------------
Copy Code code as follows:
protected void Page_Load (object sender, EventArgs e)
{
String date = DateTime.Now.ToString ();
Response.Write (date);
}
Copy Code code as follows:
<%@ Page language= "C #" autoeventwireup= true "codebehind=" WebForm1.aspx.cs "inherits=" cache. WebForm1 "%>
<%@ OutputCache duration= "Ten" varybyparam= "None"%>
<!---Adding this code means adding this page cache for 10 seconds, within 10 seconds, the Refresh page will read the cached page value and no longer perform the Page_Load method.
The Page_Load method is performed once every 10 seconds-->
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<title></title>
<body>
<div>
</div>
</body>
<%@ OutputCache duration= "Ten" varybyparam= "none"%> this instruction tag adds a cache to the page, Duration this parameter specifies a page cache time of 10 seconds. VaryByParam This specifies the page parameter, which is the case, if this page we can write the instruction tag as <%@ OutputCache duration= "varybyparam=" postid;update The parameter is separated from the parameter by a semicolon, and that's it. Each individual page is cached, and he caches the postid=2536603&update=1 or postid=1&update=2 and the different parameter pages all cached. An easy way to do this is to <%@ OutputCache duration= "Ten" varybyparam= "*"%>, and to cache pages with different parameters under the current page.
Asp. NET does not execute the page life cycle and the related code, but uses the cached page directly, the simple understanding is also in my annotation.
--------------------------------------------------------------------------------
Four, control caching
--------------------------------------------------------------------------------
1.ObjectDataSource such a data source control, you can find the appropriate properties in the property bar, to set up, 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
Copy Code code as follows:
protected void Page_Load (object sender, EventArgs e)
{
String date = DateTime.Now.ToString ();
TextBox1.Text = date;
}
Copy Code code as follows:
<%@ Page language= "C #" autoeventwireup= true "codebehind=" WebForm1.aspx.cs "inherits=" cache. WebForm1 "%>
<%@ OutputCache duration= "Ten" varybycontrol= "TextBox1"%>
<!--VaryByControl parameters are controls to be cached id-->
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<title></title>
<body>
<form id= "Form1" runat= "Server" >
<div>
<asp:textbox id= "TextBox1" runat= "Server" ></asp:TextBox>
</div>
</form>
</body>
The TextBox control here is cached, where the cache time is 10 seconds, that is, in 10 seconds asp.net will not execute the page life cycle and related code, but directly use the cached page.
--------------------------------------------------------------------------------
V. Cache dependencies
--------------------------------------------------------------------------------
Copy Code code as follows:
protected void Page_Load (object sender, EventArgs e)
{
String str = "";
if (cache["key"] = = null)
{
str = System.IO.File.ReadAllText (Server.MapPath ("TextFile1.txt")); Reading data from a TextFile1.txt file
CacheDependency DP = new CacheDependency (Server.MapPath ("TextFile1.txt"))//create 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 caching dependent on other resources, and when a dependency changes, the cached entry items are automatically removed from the cache. A cache dependency can be a file, a directory, or a key to another object in the cache of an application. If a file or directory changes, the cache expires.
--------------------------------------------------------------------------------
Vi. setting up caching in configuration files
--------------------------------------------------------------------------------
Copy Code code as follows:
<system.web>
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<addname= "Productitemcacheprofile" duration= "/>"
</outputCacheProfiles>
</outputCacheSettings>
</caching>
</system.web>
Copy Code code as follows:
<%@ Page language= "C #" autoeventwireup= true "codebehind=" WebForm1.aspx.cs "inherits=" cache. WebForm1 "%>
<%@ OutputCache cacheprofile= "Productitemcacheprofile" varybyparam= "None"%>
<!--here CacheProfile parameters are maintained in the configuration file with one to-->
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<title></title>
<body>
<div>
</div>
</body>
This adds a page with a cache of 60 seconds to the page.
--------------------------------------------------------------------------------
Vii. Cached Callback functions
--------------------------------------------------------------------------------
Copy Code code as follows:
protected void Page_Load (object sender, EventArgs e)
{
String str = "";
if (cache["key"] = = null)
{
str = System.IO.File.ReadAllText (Server.MapPath ("TextFile1.txt")); Reading data from a TextFile1.txt file
CacheDependency DP = new CacheDependency (Server.MapPath ("TextFile1.txt"))//create cache dependency DP
Cache.Insert ("Key", STR, DP, DateTime.Now.AddSeconds, Cache.noslidingexpiration, Cacheitempriority.low, CacheItemRemovedCallback);
CacheItemPriority This parameter is the priority of the cache he has a variety of levels, in order to prevent cache from full when the system itself to delete the cache priority to abolish the cache, followed by the name of the callback function.
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"]);
}
}
public void CacheItemRemovedCallback (string key, object value, CacheItemRemovedReason reason)//The callback function for cache removal, be sure to keep the The last parameter in the Cache.Insert () method has the same name.
Here the delegate is used and you can see it in Cache.Insert (), so the format can only be written in the way I write it.
{
System.IO.File.WriteAllText (Server.MapPath ("Log.txt"), "cache removal reason is:" +reason. ToString ());
}
The callback function in the example is written to generate a log.txt that records the reason for each cache removal.
--------------------------------------------------------------------------------
Viii. cache settings in the configuration file
--------------------------------------------------------------------------------
Our server has the ability to turn on caching, caching can reduce the time you visit the site when the website in the server in the compile times, greatly accelerate the speed of your site, if you need to make frequent updates to your site, you can consider temporarily reduce the cache time, or temporarily shut down the cache
Please put the following code into the Web.config file inside the root directory of your site;
1. In web.config to set the time to reduce the cache, please use the following definition in the Web.config
<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 close the caching function of a page, please 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 of the entire program, please 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>