1. How does cache work.
Cache is a public memory disk allocated to the server.
The so-called public cache allows any client browser to access it through the background code when it is created. It targets all users, and session is also a piece of memory on the server, however, it targets a single user. It is a memory block of the server, that is, each cache occupies server resources once it is created. So from this point, we can say: the more cache, the better.
The cache has a time limit. If it exceeds the expiration time set by the server, it will be recycled by the server.
Cache can store any object
Ii. How to create and destroy the cache.
Create Cache
In. In the. NET environment, use the cache. insert (string key, object O) method. The key represents the cache ID, and O represents the object stored in the cache.
Destroy cache.
In the cache. Remove (string key) method, the key represents the cache ID.
Call cache.
Cache supports packing/unpacking. For example, you can cache a DataSet object DS through. insert ("dscache", DS) is stored in the cache. You can use dataset DS = (Dataset) cache ["dscache"] to access it.
Iii. When to use cache.
Cache is generally used when data is relatively fixed and frequently used. For example, you can store product information in the invoicing system into the cache, and call the cache when the user calls the product information, which greatly reduces the interaction between the user and the database, improves system performance. On the contrary, the cache is not suitable for scenarios with fast data changes and narrow application scope. For example, you can save a specific purchase order to the cache.
4. cache call considerations.
The cache has a time limit. When the expiration time set by the server is exceeded, it will be recycled by the server. When the cache is recycled, the corresponding memory block is cleared. When the object is accessed through cache ["cachekey"] Again, the return value is null. Therefore, exceptions may occur in the following calls:
Dataset DS = (Dataset) cache ["cacheds"];
Datarow DR = Ds. Table [0]. Row [0]; // error. DS is null, and Table 0 does not exist.
5. Usage of Cache
ASP. NET cache is an important way to improve system performance. It uses the "recently used" principle (a least-recently-used algorithm ). Cache is often used to store database data during database access.
1. Add cache:
The cache adding methods include add () or insert (). The two methods are almost similar, but the inser method can use an optional parameter, that is, the default parameter, to add the cache:
Cache. Add (
Keyname, // cache name
KeyValue, // the object to be cached
Dependencies, // dependency
Absoluteexpiration, // absolute expiration time
Slidingexpiration, // relative expiration time
Priority, // priority
Cacheitemremovedcallback); // an event is triggered when the cache expires.
2. cache dependencies:
You can set the cache's timeliness through the file dependency, other cache dependencies, database dependencies, and expiration time methods. When the file changes, the dependent cache items change, the database changes, or the expiration time, the cache is invalid and may cause certain events.
2.1 file dependency:
Cachedependency filedepends = new cachedependency (server. mappath ("northwind. xml "));
Cache. insert ("gridviewdataset", dsgrid, filedepends );
In this example, the cache is dependent on the northiwind. xml file:
2.2 Other cache item dependencies:
String [] filedependsarray = {server. mappath ("northwind. xml ")};
String [] cachedependsarray = {"depend0", "depend1", "depend2 "};
Cachedependency cachedepends = new cachedependency (filedependsarray, cachedependsarray );
Cache. insert ("gridviewdataset", dsgrid, cachedepends );
In this example, the northwind. xml file dependency and depend0, depend1, and depend2 cache items are set.
Depend0, depend1, and depend2 are the other three caches.
If no file dependency is required, you can set it to null.
2.3 expiration time setting:
Absoluteexpiration can be used to set the absolute cache expiration time, for example:
Cache. insert ("gridviewdataset", dsgrid, null, datetime. Now. addminutes (30), cache. noslidingexpiration );
The cache will expire 30 minutes after it is added.
You can set the relative expiration time for noslidingexpiration. If the cache is not accessed within the time specified by noslidingexpiration, the cache expires. If there is access during this time period, the cache expiration time is reset to the original value, for example, nosexpingexpiration = 20.
The cache expires if it is not accessed within 20 minutes. If it is accessed for 19 minutes each time, the cache will never expire.
Cache. insert ("maid", dsgrid, null, cache. noabsoluteexpiration, timespan. fromseconds (30 ));
3. Priority:
Priority attribute value and meaning:
Priority Value
Description
Notremovable
Items with this priority will not be evicted.
High
Items with this priority level are the least likely to be evicted.
Abovenormal
Items with this priority level are less likely to be evicted than items assigned normal priority.
Default
This is equivalent to normal.
Normal
The default value.
Belownormal
Items with this priority level are more likely to be evicted than items assigned normal priority.
Low
Items with this priority level are the most likely to be evicted.
4. Handle cache invalidation events:
Using system;
Using system. Data;
Using system. configuration;
Using system. Web;
Using system. Web. Security;
Using system. Web. UI;
Using system. Web. UI. webcontrols;
Using system. Web. UI. webcontrols. webparts;
Using system. Web. UI. htmlcontrols;
Using system. Web. caching; // necessary for cachedependency
Using system. xml; // necessary for XML stuff
Public partial class _ default: system. Web. UI. Page
{
Public static cacheitemremovedcallback onremove = NULL;
Protected void page_load (Object sender, eventargs E)
{
Creategridview ();
}
Private void creategridview ()
{
Dataset dsgrid;
Dsgrid = (Dataset) cache ["gridviewdataset"];
Onremove = new cacheitemremovedcallback (this. removedcallback );
If (dsgrid = NULL)
{
Dsgrid = getdataset ();
String [] filedependsarray = {server. mappath ("northwind. xml ")};
String [] cachedependsarray = {"depend0", "depend1", "depend2 "};
Cachedependency cachedepends = new cachedependency
(Filedependsarray, cachedependsarray );
Cache. insert ("gridviewdataset", dsgrid, cachedepends,
Datetime. Now. addseconds (10 ),
Cache. noslidingexpiration,
Cacheitempriority. Default,
Onremove );
Lblmessage. Text = "data from XML file .";
}
Else
{
Lblmessage. Text = "data from cache .";
}
GV. datasource = dsgrid. Tables [0];
GV. databind ();
}
Private dataset getdataset ()
{
Dataset dsdata = new dataset ();
Xmldatadocument Doc = new xmldatadocument ();
Doc. dataset. readxml (server. mappath ("northwind. xml "));
Dsdata = Doc. dataset;
Return dsdata;
}
Public void removedcallback (string cachekey,
Object cacheobject,
Cacheitemremovedreason reasontoremove)
{
Writefile ("cache removed for following reason:" +
Reasontoremove. tostring ());
}
Private void writefile (string strtext)
{
System. Io. streamwriter writer = new system. Io. streamwriter (
@ "C:" test.txt ", true );
String STR;
STR = datetime. Now. tostring () + "" + strtext;
Writer. writeline (STR );
Writer. Close ();
}
Protected void btnclear_click (Object sender, eventargs E)
{
Cache. Remove ("gridviewdataset ");
Creategridview ();
}
Protected void btninit_click (Object sender, eventargs E)
{
// Initialize caches to depend on.
Cache ["depend0"] = "This is the first dependency .";
Cache ["depend1"] = "this is the 2nd dependency .";
Cache ["depend2"] = "this is the 3rd dependency .";
}
Protected void btnkey0_click (Object sender, eventargs E)
{
Cache ["depend0"] = "this is a changed first dependency .";
}
}