ASP. NET Cache

Source: Internet
Author: User

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 item
// traverse the cache. Pay attention to system. collections. dictionaryentry: defines configurable or searchable dictionary key/value pairs
foreach (dictionaryentry temp in cache)
{< br>
response. write ("key:" + temp. key. tostring () + "value:" + temp. value. tostring ()
+ "
");
}< br> Add 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
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>

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.