In-depth understanding of asp.net Cache

Source: Internet
Author: User
Tags website performance

I. Concept of cache: Benefits and types of cache.
------------------------------------------------------------------------------ The 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

--------------------------------------------------------------------------------
Copy codeThe Code is as follows:
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 ).
--------------------------------------------------------------------------------
Copy codeThe Code is 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 + ""; // 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

--------------------------------------------------------------------------------
Copy codeThe Code is as follows:
Protected void Page_Load (object sender, EventArgs e)
{
String date = DateTime. Now. ToString ();
Response. Write (date );
}

Copy codeThe Code is as follows:
<% @ 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 specifies the page parameter, which is like this. In this case, we can write the command label as <% @ OutputCache Duration = "10" VaryByParam = "postid; update "%> parameters are separated by semicolons (;), so that each page is cached, the cached parameter pages, such as postid = 2536603 & update = 1 or postid = 1 & update = 2, are all cached. 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
Copy codeThe Code is as follows:
Protected void Page_Load (object sender, EventArgs e)
{
String date = DateTime. Now. ToString ();
TextBox1.Text = date;
}

Copy codeThe Code is as follows:
<% @ 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

--------------------------------------------------------------------------------
Copy codeThe Code is 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"); // 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

--------------------------------------------------------------------------------
Copy codeThe Code is as follows:
<System. web>
<Caching>
<OutputCacheSettings>
<OutputCacheProfiles>
<Addname = "ProductItemCacheProfile" duration = "60"/>
</OutputCacheProfiles>
</OutputCacheSettings>
</Caching>
</System. web>

Copy codeThe Code is as follows:
<% @ 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

--------------------------------------------------------------------------------
Copy codeThe Code is 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"); // 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 ());
}

The callback in this example is to generate a log.txt, which records the reason for each cache removal.
--------------------------------------------------------------------------------

8. cache settings in the configuration file

--------------------------------------------------------------------------------
Our server has enabled the cache function, which can reduce the Compilation Time of the website on the server when you visit the website, greatly accelerating the access speed of your website, if you need to update your website frequently, You can temporarily reduce the cache time or temporarily disable the cache.

Put the following code into the web. config file and put it in the root directory of your website;

1. Set the cache time reduction in web. config. Use the following definition in 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 disable the caching function 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. to disable the caching function of 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. to disable the caching function of one or more 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>

 

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.