I. Concept of cache: Benefits and types of cache.
Cache is a technology that exchanges space for time. In other words, it stores your data in the memory for a period of time, in this short period of time, the server does not read the database or the real data source, but the data you store in the memory. Here, you will wonder how to set the data to be stored and what data to store, when the storage time is set, will there be a read deviation if the real data source changes the server? Don't worry. I will talk about it later ..
Cache is an indispensable data processing mechanism for website performance optimization. It can effectively relieve database pressure. For example, the per-minute click rate of a website is 1 million, if you do not use cached static pages, there is no viewstate here (viewstate will generate a large number of strings, which is a pressure on server interaction data. Therefore, viewstate is usually disabled on pages, cache is used). You can only click this page once and read the database once. This puts pressure on the database. If cache is used here, if the cache validity period is set to 1 minute, the database is read once and the data source is cached in the memory.
The cache in asp.net is mainly divided into three types: Page cache, data source cache, and custom data cache.
Ii. Data Cache
[Csharp]
Public partial class WebForm1: System. Web. UI. Page
{
Protected void Page_Load (object sender, EventArgs e)
{
// Cache ["date"] = data to be cached. Here is a simple declaration of custom Cache.
String datastr = DateTime. Now. ToLongTimeString ();
Response. write ("first output time:" + datastr + "</br>"); // The current read time here. When you refresh the page, the time here changes.
If (Cache ["date"] = null) // determines whether a Cache with the value of date exists.
{
Cache ["date"] = datastr;
Response. write ("the second output time is:" + Cache ["date"] + "current read Time"); // The current read Time, when you refresh the page, 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 you refresh the page, the time here changes with time, will not change.
}
}
}
The above data cache does not set the cache expiration time, so the first output time is the current time (refresh the page will change ), the second output time will always be the time when the cache is saved for the first time (the page will not be refreshed ).
Next we will add some practical parameters to the data cache (the code above ).
[Csharp]
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 + ""; // The ids here is a string that reads the id value in the table from the database and uses the -- Link
If (Cache ["key"] = null)
{
Cache. insert ("key", ids, null, DateTime. now. addSeconds (40), System. web. caching. cache. noSlidingExpiration); // cache the data and set the cache time.
// "Key" is the cache key, ids is the cached value, and null is the cache dependency. cache dependency is not used here, so it is null, the following describes cache dependencies in detail.
// The cache time after null is 40 seconds
// The last parameter is the time format. ASP. NET allows you to set an absolute expiration time or sliding expiration time, but cannot be used at the same time,
// Here we set the absolute expiration time, that is, the cache data is 40 seconds after the page is not refreshed once, and will be retrieved from the database after 40 seconds.
Response. Write ("cache loaded as ---" + Cache ["key"] + "</br> ");
}
Else
{
Response. Write ("cache loaded as ---" + Cache ["key"] + "</br> ");
}
Response. Write ("load directly as ---" + ids + "</br> ");
}
Data Cache: adds time-consuming entries to an object cache set and stores them as key values. You can use the Cache. Insert () method to set Cache expiration, priority, and dependencies.
3. Page Cache
[Csharp]
Protected void Page_Load (object sender, EventArgs e)
{
String date = DateTime. Now. ToString ();
Response. Write (date );
}
[Csharp]
<% @ Page Language = "C #" AutoEventWireup = "true" CodeBehind = "WebForm1.aspx. cs" Inherits = "cache. WebForm1" %>
<% @ OutputCache Duration = "10" VaryByParam = "none" %>
<! --- The code above indicates that the page will be cached for 10 seconds. Within these 10 seconds, the page will be refreshed and the value of the page will be read and cached, And the Page_Load method will no longer be executed.
The Page_Load method is executed every 10 seconds -->
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> </title>
</Head>
<Body>
<Div>
</Div>
</Body>
</Html>
<% @ OutputCache Duration = "10" VaryByParam = "none" %> This command label adds cache for this page. The Duration parameter specifies that the page cache time is 10 seconds, varyByParam This specifies the page parameter, that is, this, for example, such a page http://www.cnblogs.com/knowledgesea/admin/EditPosts.aspx? Postid = 2536603 & update = 1, then its parameters are postid and update, in this case, the command label can be written as <% @ OutputCache Duration = "10" VaryByParam = "postid; update" %> parameters and parameters are separated by semicolons, in this way, each separate page is cached. The cached parameter pages are all cached, such as postid = 2536603 & update = 1 or postid = 1 & update = 2. You can use <% @ OutputCache Duration = "10" VaryByParam = "*" %> to cache all pages with different parameters on the current page.
ASP. NET does not execute the page lifecycle and related code, but directly uses the cached page. It is simply described in my notes.
Iv. Control Cache
1. for data source controls such as ObjectDataSource, you can find the corresponding attributes in the attribute bar and set them. I will list an example below to set the cache startup time to 10 seconds, the time type is absolute time.
<Asp: ObjectDataSource ID = "objectperformance1" runat = "server" EnableCaching = "True" CacheDuration = "10" CacheExpirationPolicy = "Absolute"> </asp: ObjectDataSource>
2. Add cache to controls without cache Properties
[Csharp]
Protected void Page_Load (object sender, EventArgs e)
{
String date = DateTime. Now. ToString ();
TextBox1.Text = date;
}
[Csharp]
<% @ Page Language = "C #" AutoEventWireup = "true" CodeBehind = "WebForm1.aspx. cs" Inherits = "cache. WebForm1" %>
<% @ OutputCache Duration = "10" VaryByControl = "TextBox1" %>
<! -- The VaryByControl parameter is the Control id to be cached -->
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> </title>
</Head>
<Body>
<Form id = "form1" runat = "server">
<Div>
<Asp: TextBox ID = "TextBox1" runat = "server"> </asp: TextBox>
</Div>
</Form>
</Body>
</Html>
The TextBox Control is cached. The cache time here is 10 seconds, that is, ASP within 10 seconds. NET does not execute the page lifecycle and related code, but directly uses the cached page.
V. cache dependency
[Csharp]
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 TextFile1.txt.
CacheDependency dp = new CacheDependency (Server. MapPath ("TextFile1.txt"); // create cache dependency dp
Cache. Insert ("key", str, dp );
Response. Write (Cache ["key"]); // data in the Response File
}
Else
{
Response. Write (Cache ["key"]);
}
}
Cache dependencies make the cache dependent on other resources. When the dependencies are changed, the cache entries are automatically removed from the cache. Cache dependencies can be files, directories, or keys with other objects in the application's Cache. If the file or directory changes, the cache will expire.
6. Set cache in the configuration file
[Csharp]
<System. web>
<Caching>
<OutputCacheSettings>
<OutputCacheProfiles>
<Addname = "ProductItemCacheProfile" duration = "60"/>
</OutputCacheProfiles>
</OutputCacheSettings>
</Caching>
</System. web>
[Csharp]
<% @ Page Language = "C #" AutoEventWireup = "true" CodeBehind = "WebForm1.aspx. cs" Inherits = "cache. WebForm1" %>
<% @ OutputCache CacheProfile = "ProductItemCacheProfile" VaryByParam = "none" %>
<! -- Here the CacheProfile parameter is the same as that in the configuration file -->
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> </title>
</Head>
<Body>
<Div>
</Div>
</Body>
</Html>
In this way, a page with a cache of 60 seconds is added to the page.
VII. cache callback Functions
[Csharp]
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 TextFile1.txt.
CacheDependency dp = new CacheDependency (Server. MapPath ("TextFile1.txt"); // create cache dependency dp
Cache. Insert ("key", str, dp, DateTime. Now. AddSeconds (20), Cache. nosreceivingexpiration, CacheItemPriority. Low, CacheItemRemovedCallback );
// CacheItemPriority: this parameter indicates the cache priority. It is divided into multiple levels. To prevent the system from deleting the cache when the cache is full, the cache is abolished first, followed by the callback function name.
Response. Write (Cache ["key"]); // data in the Response File
}
Else
{
Response. Write (Cache ["key"]);
}
}
Public void CacheItemRemovedCallback (string key, object value, CacheItemRemovedReason reason) // This is the callback function for Cache removal. It must be consistent with the Cache. the last parameter name in the Insert () method is the same,
// Here the delegate is used. You can see it in the intermediate definition of the Cache. Insert () function, so the format here can only be signed and written according to the method I wrote.
{
System. IO. File. WriteAllText (Server. MapPath ("log.txt"), "reason for cache removal:" + reason. ToString ());
}
Author: ysq5202121