ASP. NET Cache learning experience

Source: Internet
Author: User
Tags set cookie delete cache

Speaking of Cache, I think the most important thing we think of is its improvement in program performance. When talking about website optimization, we naturally think of Cache. So what is Cache? What is the purpose of Cache?
First of all, please imagine this scenario. If we need to display a large amount of information on the homepage of a website, the information will be updated at a certain time, but the update frequency will not be very high, when a user accesses a page, a large amount of data needs to be loaded and presented from the background. If a large number of users frequently access the page, I had to constantly load and present data from the back-end database. However, because the information update frequency is not very high, almost the same information is returned every time, does this increase unnecessary server overhead? If there is a mechanism to load the information during the first access and save it temporarily, when someone visits this page, the temporary data is displayed to the user instead of requesting the server. Is this convenient? The program performance can certainly be greatly improved. The Cache we call is such a mechanism. The reason why it can greatly improve the performance of the program is that it can Cache some information, to reduce unnecessary server overhead.
After talking about this, I think you have a basic understanding of Cache. The following describes the Cache in detail in the following aspects and shows you how to use the Cache properly through relevant examples.
I. Traditional Cache
Speaking of traditional Cache, I think everyone will think of Request. QueryString (), Session, Application, Cookie, etc. I will go straight to the topic. That's right. Here I will show you how to use these traditional caches through examples.
1.1 Request. QueryString ()
When it comes to QueryString (), it is mainly used to pass the value of the page Url. It is mainly used to submit the page form through Get. The demo is as follows:
1.1.1 create a new Default. aspx page with the following layout:
<Asp: TextBox ID = "txttest" runat = "server"> </asp: TextBox>
<Asp: Button ID = "btnset" runat = "server" Text = "QueryString"
Onclick = "btnset_Click"/>
1.1.2. The cs page is processed as follows:
String name = txttest. Text;
Response. Redirect ("~ /Show. aspx? Name = "+ name );
1.1.3 create a new Show. aspx page to display the passed name value. The page has only one label.
1.1.4 perform the following processing in Page_load:
If (Request. QueryString ["Name"]! = Null)
{
Lbshow. Text = Request ["Name"]. ToString ();
}
The 1.1.5 page shows the passed name value.
1.2. Session
Session is a unique request that identifies a browser or client device and maps these requests to a single Session instance on the server. Session-specific data can be stored on the server, session is a separate global variable relative to the entire application. We usually use Session to mark whether a user is logged on, temporarily store the user's login name, Logon account, and other information. In many background management systems of websites, Session is used to mark whether a user is logged on, if you do not log on, you cannot directly access the background page. At the same time, if the user does not exchange a response to the server within the corresponding time period, the Session will expire. Some Session settings are not the focus of this section, I will explain the status management mechanism of Asp.net in the next section. Now, the following example shows how to use Session.
1.2.1. the page layout is as follows:
Asp: TextBox ID = "txttest" runat = "server"> </asp: TextBox>
<Asp: Button ID = "btnSession" runat = "server" Text = "Session"
Onclick = "btnSession_Click"/>
1.2.2. process the following on the cs page:
String name = txttest. Text;
Session ["name"] = name;
Response. Redirect ("~ /Show. aspx ");
1.2.3 create a new Show. aspx page with only one label used to display the name in the Session
The processing in Page_Load is as follows:
If (Session ["name"]! = Null)
{
Lbshow. Text = Session ["name"]. ToString ();
}
1.3 Application
Application is a global shared variable of the Application. It can also be used to store temporary information. However, most applications are used to collect Website access data. As a global shared variable, concurrency must be taken into account. Especially when collecting Website access statistics, if multiple people access the website at the same time, in order to accurately count the number of visitors, we need to lock the Application and process the accessed data before unlocking. This can greatly reduce the concurrency, this section describes how to use the Application to collect Website access statistics.
1.3.1 first add a Global. asax and then perform the following processing in the Application_Stat event:
Protected void Application_Start (object sender, EventArgs e)
{
Application. Lock ();
{
If (Application ["count"] = null) // set the count to 0 when the program starts.
{
Application ["count"] = 0;
}
}
Application. UnLock ();
}
1.3.2. Then, perform the following processing in the Seesion_Start event. If a new user accesses the website, add 1 to the number of visitors.
Protected void Session_Start (object sender, EventArgs e)
{
Application. Lock ();
{
If (Application ["count"]! = Null)
{
Application ["count"] = (int) Application ["count"] + 1;
}
}
Application. UnLock ();
}
1.3.3 If we need to display it on the front-end page, we can directly use Application ["count"] to obtain the number of visitors to the website. Here are two sentences: What we do here is Website access statistics. If we want to do online statistics, it is also very simple. At this time, we need to process events in Seesion_End, reduce the number of online users by one. If you are interested, you can study it on your own.
Cookie 1.4
There are also cookies in Javascript. Here we mainly talk about cookies in Asp.net.
The following example shows how to use cookies under Asp.net.
1.4.1. The new page layout is as follows:
<Table>
<Tr> <td> <asp: Label ID = "Label1" runat = "server" Text = "set Cookie value:"> </asp: Label> </td>
<Td> <asp: TextBox ID = "txtcookie" runat = "server"> </asp: TextBox> </td> </tr>
<Tr> <td> <asp: Label ID = "Label2" runat = "server" Text = "read Cookie value:"> </asp: label> </td> <asp: TextBox ID = "txtxs" runat = "server"> </asp: TextBox> </td> </tr>
<Tr> <td> <asp: Button ID = "btnsz" runat = "server" Text = "set" onclick = "btnsz_Click"/> </td>
<Td> <asp: Button ID = "btnxs" runat = "server" Text = "show" onclick = "btnxs_Click"
Style = "height: 21px"/> </td> </tr>
</Table>
1.4.2. processing on the cs page is as follows:
// Set Cookie
Protected void btnsz_Click (object sender, EventArgs e)
{
// Response. Cookies ["Name"] = txtcookie. Text; is another way to set Cookies
HttpCookie cookie = new HttpCookie ("Name ");
Cookie. Value = txtcookie. Text;
Cookie. Expires = DateTime. Now. AddDays (1 );
Response. Cookies. Add (cookie );
Response. Write ("<script> alert ('set successfully! ') </Script> ");
}
// Read Cookie
Protected void btnxs_Click (object sender, EventArgs e)
{
If (Request. Cookies ["Name"]. Value! = Null)
{
Txtxs. Text = Request. Cookies ["Name"]. Value. ToString ();
}
Else
{
Response. Write ("<script> alert ('the Cookie read does not exist! ') </Script> ");
}
}
Here is a simple demonstration of Cookie setting and reading. If we do not set the Cookie expiration time, it is a non-persistent Cookie and will soon become invalid, if the expiration time is set, the Cookie can be stored in local files, SQL Server, or other services.
Ii. Page output Cache
The so-called page output cache mechanism is to cache the content of the Asp.net page into the server memory. When the page is requested for the first time, the page will be cached. When the page is requested again, directly send the page back to the user from the cache until the cache expires and the page is cached again. The page cache is mostly used for pages that require a lot of processing to be compiled, and the page content does not change frequently, just like the example I mentioned at the beginning of the article.
Here is a simple example to show you how to cache page output.
2.1 create An aspx page with only one label and one button on it. The layout is as follows:
<Asp: Label ID = "lbshowTime" runat = "server" Text = ""> </asp: Label>
<Br/>
Actual page time: <asp: Substitution ID = "Substitution1" runat = "server" MethodName = "GetCurrentTime"/>
<Asp: Button ID = "btnST" runat = "server" Text = "ShowTime" onclick = "btnST_Click"/>
2.2. perform the following operations on the aspx page:
Introduced under the <% @ page %> node
<% @ OutputCache Duration = "30" VaryByParam = "none" %>
This Code indicates that the current page is cached for 30 seconds.
2.3. Then, we will handle the following in the Cilick event of the Button on the. cs page:
Protected void btnST_Click (object sender, EventArgs e)
{
LbshowTime. Text = DateTime. Now. ToString ();
}
2.4 After running, we found that no matter how we click to assign a value to the label, the value of the label has not changed. After one minute, we click the set button again to find that the time has changed, this is because our Cache time expires and the new time will be cached. Careful friends may find that the highlighted parameter we introduced above is VaryByparam. What is the function of this parameter? This parameter indicates that the cached content is updated on a page based on the name/value pairs (parameters) sent by POST or GET. Multiple parameters are separated by semicolons, for example, http: // localhost: 5435/Show. aspx? Id = 4 & name = Olive. You can set <% @ OutputCache Duration = "30" VaryByParam = "p; name" %>. If you do not want to change the cached content based on any parameters, set the value to none. If you want to update the cache by changing all the parameter values, set the attribute to asterisk (*). here, we hope you will note that we set cache for each parameter separately, rather than sharing one cache for all parameters. In fact, <% @ OutputCache %> supports a total of five attributes (Duration, VaryByParam, Location, VaryByCustom, VaryByHeader). Two attributes (Duration, VaryByParam) are required, these two attributes have been described above. The other three attributes VaryByHeader modify cache entries based on changes in the specified header. VaryByCustom allows you to specify custom changes (for example, "Browser") in global. asax "). VaryByHeader and VaryByCustom are mainly used to customize the appearance or content of the page based on the client accessing the page. The same URL may need to be rendered and output for both the browser and mobile client. Therefore, different content versions must be cached for different clients. Alternatively, the page may have been optimized for IE. For Netscape or Opera, the optimization function should be canceled. 3. Partial page cache.
In the previous section, we talked about the page output cache, that is, the whole page is cached in memory. However, in actual development, it is not necessary to cache all the page memory, in this case, we can use partial page cache. Partial page cache can be composed of two parts: User Control cache and partial cache.
3.1 User Control Cache
For user control caching, we only need to create a new user control page, and then add <% @ OutputCache %> to its aspx for relevant cache settings. Note that besides the Location attribute, user Controls also support all attributes supported by OutputCache on Web forms. The user control also supports the OutputCache attribute named VaryByControl, which changes the control cache based on the value of the user control member. If VaryByControl is specified, You can omit VaryByParam. By default, each user control on each page is cached separately. However, if a user control does not change with the page in the application and the same name is used on all pages, you can set the value of the Shared parameter to "true ", this parameter allows the cached version of the control to be used on all pages that reference the control. 3.2 local cache
The so-called partial page cache can be understood as a page replacement cache. In actual development, we sometimes need to cache most of the page content, however, a small part of the content does not need to be cached, so local cache can be used. The Substitution control is used. The following example shows how to perform partial page caching.
3.2.1 create An aspx page with the following layout:
<Asp: Label ID = "lbshowTime" runat = "server" Text = ""> </asp: Label>
<Br/>
Actual page time: <asp: Substitution ID = "Substitution1" runat = "server" MethodName = "GetCurrentTime"/>
<Asp: Button ID = "btnST" runat = "server" Text = "ShowTime" onclick = "btnST_Click"/>
3.2.2 Add the following content to the aspx header: <% @ OutputCache Duration = "30" VaryByParam = "none" %>
Cache the page
3.2.3 perform the following operations on the cs page:
Protected void btnST_Click (object sender, EventArgs e)
{
LbshowTime. Text = DateTime. Now. ToString ();
}
Protected static string GetCurrentTime (HttpContext hc)
{
Return DateTime. Now. ToString ();
}
Here, we need to pay special attention to a property of the Substitution control on the front-end page: the value of MethodName is our background function GetCurrentTime. This attribute is used to obtain or set the name of the method called when the Substitution control is executed. This method must comply with the following three criteria: 1. This method must be defined as a static method; 2. This method must accept parameters of the HttpContext type; 3. This method must return a value of the String type. The Substitution control automatically calls the method defined by the MethodName attribute during running. The string returned by this method is the content to be displayed on the position of the Substitution control on the page. If all outputs are cached on the page, the page runs and caches the output of the first request. Subsequent requests will be cached, and other code on the page will not run. However, the Substitution Control and Its Related methods are executed at each request, and the dynamic content represented by the control is automatically updated, thus implementing the overall cache and local changes.
4. Application cache (System. web. caching. cache) page-level and user control-level Cache is indeed a way to quickly and easily improve site performance, but in ASP. in addition to page-level and user control-level Cache, the Cache class provided by Asp.net is more flexible. web. caching. cache), we can use the Cache object to store any serializable data objects, and control the Cache entry expiration method based on the combination of one or more dependencies. These dependencies can include the time since the item was cached, the time since the item was last accessed, changes to files and/or folders, and changes to other cache items, after slight processing, you can also include changes to specific tables in the database. If you are interested, you can download and use the following, including various Cache Usage methods, including using Cache dependencies for caching purposes.
V. distributed cache
The Caching methods we mentioned above are based on the single-server cache. In actual development, if we build a distributed cache system, these will not meet our needs. Because the distributed cache is rarely used at this stage, we do not know much about this part, so we can't talk about it. I read about the distributed cache on the Internet, many of my friends recommend using Memcached to create a distributed cache. Here is just a brief introduction to Memecahed. If you are interested, let's get to know it. Memcached is a high-performance distributed memory cache server developed by Brad Fitzpatric, Danga Interactive under LiveJournal. The general purpose is to reduce the number of database accesses by caching database query results, so as to speed up dynamic Web applications and improve scalability. It maintains a hash table by opening up a region in the memory to speed up page access, which is relatively independent from the database. Any web server can update or delete cache items, and all other servers can detect these updates at the next access.

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.