asp.net--Caching (Cache)

Source: Internet
Author: User

  1. Basic    ? Definition

Caching (cache) is a space-for-time technology that exists in many parts of a computer to keep common data from slow devices in a fast device, taking data directly from a fast device, such as CPU level two cache, memory, and window file read cache.

    ? Features

If every time you enter the page query database generated page content, if the traffic is very large, then the site performance will be very poor. And if only the first time to query the database generated page content, and then directly output content, you can improve the performance of the system, so no matter how many people access, are only access to the database: database pressure unchanged.

The cache has a failure problem, in order to ensure that the data read from the cache and slow data (database) consistent, need to be in slow data (database) corresponding data changes, the cache of the corresponding data (cache dependency).

    ? Category

Caching is the first way to improve the performance of a Web site, just as the index is the first way to improve database performance, and the cache is divided into three main categories: page caching (moderation), data source caching (least flexible), and data caching (flexibility).

  2. Application    ? Frame

Note : The left side is the browser, the right is the server, the browser requests a page to the server, such as the list page list.aspx, the list page calls the business layer, the business layer calls the data layer, access the database way to read the data, and then return the generated data, The HTML code is generated and returned to the browser, which is to create the business layer, and working with the data layer, and the database is the most time-consuming, database and database files to deal with, the first level than the first time and resource-intensive. To solve this problem, we can cache the returned HTML generated data and go directly to the cache the next time we revisit it, which greatly improves the efficiency of the access.

 3. Example Demo    ? Demonstrates the difference between a cache and no
<span style= "Font-family:microsoft yahei;font-size:14px;" ><strong>using system;using system.collections.generic;using system.linq;using System.Web;using        system.web.ui;using system.web.ui.webcontrols;namespace cache{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 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 exists a cache with a value of date {//cache["date"] = Datastr; Set the expiration time for the cache//the following parameters correspond to the design cache expiration key, value, cache dependency, absolute expiration time, sliding expiration time (last time mainly) Cache.Insert ("Date", Da                TASTR, NULL, DateTime.Now.AddSeconds (+), System.Web.Caching.Cache.NoSlidingExpiration);   Response.Write ("The second output time is:" + cache["date"] + "The current time read here"); The current time that is read hereWhen the page is refreshed, the time here changes. } else {Response.Write (cache["date"] + "Here is the time to read from the cache");//Read the time in the cache here, refresh the page, where it changes over time            and will not change. }}}}</strong></span>

    ? Category Cache-Page Cache example

Add <% @OutputCache duration= "All" varybyparam= "none"%> tag to enable page caching so that the contents of the entire page are cached, the page's ASP code, The data source is not run during the cache, but instead outputs the cached page content directly. Duration represents the cache time, in seconds, over which the time is invalidated, the second generation will be cached for another 15 seconds, and so on, Set a breakpoint at Page.load, modify the database data test, this cache is cached in the server, not on the client, because with HttpWatch or can see the request submitted to the server, but the server sees the cache is no longer execute the page class, general video, news needs to cache.

The cache is for all visitors to this page, so the pressure on the database for 1 visitors and 10,000 visitors, one visit, and 1 million visits is the same.

For page caching, we need to join the instruction set. Instruction set VaryByParam after the input parameters, such as can be by ID, instruction set for "<% @OutputCache duration=" "varybyparam=" id "%>", so that the different ID set different page cache, and the individual pages only because of different parameters, if there are multiple parameters to determine the cache, the parameter names are separated by semicolons, for example: varybyparam= "Id;name". The cache may have outdated data, so it needs to be selected on demand.

Of course, if you want any different query string to be able to create a different cache, then set varybyparam= "*", the General setting of "*" is sufficient.

You can also set the cache for a control in Webusercontrol like a page cache. Interested to try it yourself. Front Desk:
<span style= "Font-family:microsoft yahei;font-size:14px;" ><strong><%@ page language= "C #" autoeventwireup= "true" codebehind= "Cache2.aspx.cs" inherits= " Cache.cache2 "%><%@ OutputCache duration=" "varybyparam=" None "%><! DOCTYPE html>
Backstage:
<span style= "Font-family:microsoft yahei;font-size:14px;" ><strong>using system;using system.collections.generic;using system.linq;using System.Web;using System.web.ui;using system.web.ui.webcontrols;using system.data.sqlclient;using System.Data;namespace cache{Public                     Partial class Cache2:System.Web.UI.Page {protected void Page_Load (object sender, EventArgs e) {            SqlConnection con = Dbcon.createcon (); Con.            Open ();            SqlCommand cmd = new SqlCommand ("SELECT * from Login", con); SqlDataReader SDR = cmd.                       ExecuteReader ();            Listbox1.datasource = SDR;            Listbox1.datatextfield = "UserName";            Listbox1.databind (); Sdr.            Close (); Con.            Close ();        Response.Write ("Time to fetch data directly from the database:" + DateTime.Now.ToString ()); }}}</strong></span>
    ? Data source Control Cache

Add an Object data source, detailed steps refer to the following blog link, because I do not have a B layer here, so there is no longer a demonstration, I can go to try. http://blog.csdn.net/goodshot/article/details/6401551

The cache settings are simpler than before, as long as the ObjectDataSource CacheDuration (cache time: seconds) is set, Enablecaching=true. This invokes the SelectMethod specified method to execute the database query every cacheduration specified time period, and all other times it returns the cached data directly. The process cache that takes the data, during the cache, the bound control to the ObjectDataSource to the data, ObjectDataSource directly back the cached data to the control, no longer to the TypeName point to the class to data.

Work Flow chart:

If the cache is present, the data in the cache is returned directly to the control, otherwise the lookup of the corresponding class is executed, and the data is returned finally.

To set the property map:

This causes the Page object to refresh, but the data source is not read from the database.  

You can also set the HTML face:
<span style= "Font-family:microsoft yahei;font-size:14px;" ><strong><asp:objectdatasource id= "ObjectDataSource1" runat= "Server" enablecaching= "True" cacheduration= "cacheexpirationpolicy=" Absolute "></asp:objectdatasource></strong></span >

4. Summary

Cache is a space in exchange for time technology, we know there are sessions and cookies, and so on, the understanding of the cache is just beginning, with the future of learning will continue to deepen, I hope in the future study continue to deepen, this is only their initial understanding.



asp.net--Caching (Cache)

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.