I. cache classification in ASP. NET, three types in total Page output cache, page fragment cache, and page data cache Ii. Page output Cache You can use the page output cache to improve the performance of the web site. YesIt caches page output and sends cached copies to respond to browser requests, instead of executing the page each time when requesting the page.. For example, your website contains a page for displaying product information retrieved from the database table. By default, each time a user accesses a product page, the page must be executed and retrieved from the database. If the page output cache is enabled, the page is executed only once and data is retrieved only once from the database. This reduces the number of web applications.ProgramAnd database server load. To enable the page output cache, the page contains the following page processing commands: <% @ Outputcache duration = "60" varybyparam = "NONE" %> For example: <% @ Page Language = "C #" %>
<% @ Outputcache duration = "300" varybyparam = "NONE" %>
<% @ Import namespace = "system. Data" %>
<% @ Import namespace = "system. Data. sqlclient" %> <Script language = "C #" runat = "server"> Void page_load (Object sender, eventargs E)
{
Sqlconnection connorthwind;
String strselect;
Sqlcommand cmdselect;
Sqldatareader dtrproducts; Connorthwind = new sqlconnection (@ "Server = localhost; Integrated Security = sspi; database = northwind ");
Strselect = "select * from products where productid = 1 ";
Cmdselect = new sqlcommand (strselect, connorthwind );
Connorthwind. open ();
Dgrdproducts. datasource = cmdselect. executereader (commandbehavior. singlerow );
Dgrdproducts. databind ();
Connorthwind. Close (); String strtime = datetime. Now. tostring ();
Lblmessage. Text = strtime;
}
</SCRIPT>
<HTML>
<Head> <title> productpage. aspx </title>
<Body> <Asp: DataGrid
Id = "dgrdproducts"
Cellpadding = "10"
Runat = "server"/>
<HR>
<Small> last updated: <asp: Label
Id = "lblmessage"
Font-bold = "true"
Forecolor = "blue"
Runat = "server"/> </small> </Body>
</Html> This example shows the specific product information retrieved from the northwind database. This page is cached for 5 minutes. Note: There is no guarantee that the cached items will always be stored in the output cache of the page. If the system resources are insufficient, ASP. NET The framework clears cache items from the cache. Attribute Duration The cache time, in seconds. Attribute Varybyparam Indicates that a page request contains parameters. ( Query string parameters or form field parameters ) How the page is cached. This attribute can take the semicolon as the separator parameter list, or the following two special values: None ------ Indicates that different cached versions of the page are not created even if the page is requested with different parameters. *----------- Indicates that different parameters are included when the page is requested, and different cache books are created on the page. For example: Http: // locathost/P. aspx? PID = 4 Http: // localhost/P. aspx? PID = 5 <% @ Outputcache duration = "300" varybyparam = "PID" %> This command queries string Parameters PID Of
Set cache location --- Attribute Location ( From Outputcachelocation A value of the enumeration type. ) : Any --- Default value. Pages can be cached anywhere, including servers, downstream servers, and browsers. Client --- The page output is only cached in the browser. Downstream ---- The page output is only cached on downstream servers. None ---- No page cache operation is performed. Server ---- The page is only cached on the server. Use Httpcachepolicy Class -- Precise Control of page cache behavior Where Setexpires () The expiration date of the page, Setcacheability () Indicates how the page is cached. Setcachability () Method Httpcacheability Values in the enumerated type: Nocache --- Prevent any page from being used Cache-control: No-Cache Header to cache. Private -- Indicates that the page should not be cached by the proxy server, but can be cached by the browser. Default value. Public -- Indicates that the page can be cached by the browser and proxy server. Server -- Indicates that the page can only be cached on the server. 3. Use Page fragment Cache Page segment cache is implemented through user service controls. By creating a separate user control for each area of the page, you can define different areas of the page. You can use Outputcache Command to describe how to cache the control output. Note: By default, the output of each user control is cached independently. To share the same output cache across multiple user controls, you can use Shared Attribute <% @ Outputcache duration = "60" varybyparam = "*" shared = "true" %> Page fragment cache restrictions: Because the control is cached, you cannot program the attributes of the user control on the page, nor use the data binding syntax for the cached user control. 4. Use Page data cache Each ASP. NET application has a cache object that is available until the application restarts. Cache. insert ("T1", "goodtyl ");// Add item
Cache. insert ("T2", "Weiwei ");
Cache. insert ("T3", "Haha ");
Cache. Remove ("T3"); // remove items
// Traverse the cache. Note system. Collections. dictionaryentry: defines dictionary key/value pairs that can be set or retrieved.
Foreach (dictionaryentry temp in cache)
{
Response. Write ("key:" + temp. Key. tostring () + "value:" + temp. value. tostring () + "<br> ");
}
Add cache file dependency: When adding a file dependency, You can associate this item with a file. If the file changes, this item is automatically deleted from the cache. For example, cache. insert ("mi", "hello", new system. web. caching. cachedependency (mappath ("a.txt" )));;if a.txt is modified, mi is automatically deleted from the cache. Add cache trigger dependency : Updates an item in the cache as long as the record of the database table changes. You need to use sqlserver trigger and xp_cmdshell to extend the stored procedure. Create trigger updatecache
On Products
For update, delete, insert
As
Declare @ cmd varchar (200)
Select @ cmd = 'echo '+ Cast (getdate () as varchar (50) +
'> C: \ tablechange.txt'
Exec master .. xp_mongoshell @ cmd, no_output Code: <% @ Page Language = "C #" %>
<% @ Import namespace = "system. Data" %>
<% @ Import namespace = "system. Data. sqlclient" %> <Script language = "C #" runat = "server"> Void page_load (Object sender, eventargs E)
{
Dataset dstproducts = (Dataset) (Cache ["productsds"]);
If (dstproducts = NULL)
{
Dstproducts = getproducts ();
Cache. insert ("Products", dstproducts, new cachedependency ("C: \ tablechange.txt "));
}
Dgrdproducts. datasource = dstproducts;
Dgrdproducts. databind ();
} Dataset getproducts (){
Sqlconnection connorthwind;
String strselect;
Sqldataadapter dadproducts;
Dataset dstproducts; Connorthwind = new sqlconnection (@ "Server = localhost; Integrated Security = sspi; database = northwind ");
Strselect = "select top 20 * from products order by productid ";
Dadproducts = new sqldataadapter (strselect, connorthwind );
Dstproducts = new dataset ();
Dadproducts. Fill (dstproducts, "productsds ");
Return dstproducts;
} </SCRIPT> <HTML>
<Head> <title> databasedependency. aspx </title>
</Head>
<Body> <Asp: DataGrid
Id = "dgrdproducts"
Runat = "server"/> </Body>
</Html>
Add cache key dependency : <% @ Page Language = "C #" %>
<Script language = "C #" runat = "server"> Void updateitem1 (Object S, eventargs E)
{
Cache ["Item1"] = txtnewvalue. text;
} Void updateitem2 (Object S, eventargs E)
{
String arrkeydepends = ("Item1 ");
Cache. insert ("item2", txtnewvalue. Text, new cachedependency (server. mappath (arrkeydepends), system. datetime. Now ));
} </SCRIPT> <HTML>
<Head> <title> keydependency. aspx </title>
<Body>
<Form runat = "server"> <Asp: textbox
Id = "txtnewvalue"
Runat = "server"/>
<P>
<Asp: button
TEXT = "Update Item1"
Onclick = "updateitem1"
Runat = "server"/>
<Asp: button
TEXT = "Update item2"
Onclick = "updateitem2"
Runat = "server"/> <HR> Item1 = <% = cache ["Item1"] %>
<Br>
Item2 = <% = cache ["item2"] %> </Form>
</Body>
</Html>
Create an absolute expiration Policy : Cache. insert ("time", strtime, null, datetime. Now. addminutes (1), cache. noslidingexpiration ); Create a relative expiration Policy : Cache. insert ("time", strtime, null, cache. noabsoluteexpiration, timespan. fromminutes (1 )); Set cache item priority : Cache. insert ("my", "hello", null, cache. noabsoluteexpiration, cache. noslidingexpiration, cacheitempriority. High, null ); Create cache callback Method : When inserting an item into the cache, You can associate a callback method with this item. For whatever reason, the callback method is automatically executed as long as the item is deleted from the cache. The most obvious callback application is to automatically reload an item to the cache when it expires. Sample Code: <% @ Page Language = "C #" %>
<Script language = "C #" runat = "server"> Public static cacheitemremovedcallback onremove;
// Cacheitemremovedreason Indicates the reason why an item is deleted from the cache.
Void itemremoved (string stritemkey, object objitemvalue, cacheitemremovedreason objremovedreason)
{
String strlogentry; Strlogentry = "item with value" + objitemvalue. tostring ();
Strlogentry = "removed at" + system. datetime. Now. tostring ("T ");
Strlogentry = "because of" + objremovedreason. tostring ();
If (application ["cachelog"] = NULL)
{
Application ["cachelog"] = new arraylist ();
}
// Application ["cachelog"]. Add ("strlogentry ");
// BEEP ();
} Void btnaddcache_click (Object S, eventargs E)
{
Onremove = new cacheitemremovedcallback (itemremoved );
Cache. insert ("myitem", txtnewvalue. Text, null, datetime. Now. addseconds (10), cache. noslidingexpiration, cacheitempriority. High, onremove );
} Void btnremovecache_click (Object S, eventargs E)
{
Cache. Remove ("myitem ");
} Void page_prerender (Object S, eventargs E)
{
Dgrdcachelog. datasource = application ["cachelog"];
Dgrdcachelog. databind ();
}
</SCRIPT> <HTML>
<Head> <title> cachecallback. aspx </title>
<Body>
<Form runat = "server"> <H2> cache log </H2>
<Asp: DataGrid
Id = "dgrdcachelog"
Cellpadding = "8"
Runat = "server"/>
<P>
<Asp: textbox
Id = "txtnewvalue"
Runat = "server"/>
<P>
<Asp: button
Id = "btnaddcache"
TEXT = "add to cache! "
Onclick = "btnaddcache_click"
Runat = "server"/> <Asp: button
Id = "btnremovecache"
TEXT = "Remove from cache! "
Onclick = "btnremovecache_click"
Runat = "server"/> <Asp: button
TEXT = "Refresh page! "
Runat = "server"/> </Form>
</Body>
</Html>
Note: This article from http://www.cnblogs.com/cgdaini/archive/2009/08/27/1554764.html