ASP. NET provides a complete caching engine that allows you to store and retrieve arbitrary objects through HTTP requests.
The cache lifetime is the same as that of the application. That is, when the application restarts, the cache is created again.
Add data to cache
1. Add an item to the cache by specifying its key and Value
Cache ["TXT"] = "";
2. add items to the cache by using the insert (reload insert method) Method
Cache. insert ("TXT", "");
The following code sets a relative expiration Policy. It inserts an item, which expires 10 minutes after the last access. Note:
Datetime. maxvalue indicates that there is no absolute expiration policy for this item.
Datetime absoluteexpiration = datetime. maxvalue;
Timespan slidingexpiration = timespan. fromminutes (10 );
Cache. insert ("TXT", "A", null,
Absoluteexpiration, slidingexpiration,
System. Web. caching. cacheitempriority. High, null );
3. Use the add method to add items to the cache.
The add method has the same signature as the insert method, but it returns the object that represents the added item.
Datetime absoluteexpiration = datetime. maxvalue;
Timespan slidingexpiration = timespan. fromminutes (10 );
Object OJB = (string) cache. Add ("TXT", "A", null,
Absoluteexpiration, slidingexpiration,
System. Web. caching. cacheitempriority. High, null );
String STR = (string) OJB;
Response. Write (STR );
The result is displayed as ""
The add method is not flexible in use. Seven parameters must be provided when the add method is used, and the insert method is reloaded four times. We can
To select an appropriate overload method as needed
Get data from Cache
Method 1:
String STR = (string) cache. Get ("TXT ");
Response. Write (STR );
Method 2:
String str1 = (string) cache ["txt1"];
Response. Write (str1 );
View All data in the cache
System. Text. stringbuilder sb = new system. Text. stringbuilder ("", 100 );
Foreach (dictionaryentry caches in cache)
{
SB. append ("Key ="). append (caches. Key. tostring (). append ("<br> ");
SB. append ("value ="). append (caches. value. tostring (). append ("<br> ");
}
Response. Write (sb. tostring ());
View the number of items in the cache
Int COUNT = cache. count;
Response. Write (count. tostring ());
Delete data from the cache
Cache. Remove ("TXT ");
Objects that make the cache have file dependencies or key dependencies
Create a button on the page to check whether the cache exists.
When the form is started, we create a cache with the name = "txt2" and the value = dataset Ds.
This cache is associated with myfile. xml. When the myfile. xml file changes, txt2cache is automatically deleted.
Private void page_load (Object sender, system. eventargs E)
{
If (! Ispostback)
{
String filepath = mappath ("myfile. xml ");
Sqlconnection con = new sqlconnection ("uid = sa; database = pubs ;");
Sqldataadapter da = new sqldataadapter ("select * from authors", con );
Dataset DS = new dataset ();
Da. Fill (DS );
System. Web. caching. cachedependency cachedependencyxmlfile = new
System. Web. caching. cachedependency (filepath );
Cache. insert ("txt2", DS, cachedependencyxmlfile );
}
}
To monitor changes in the authors table of the pubs Database
You can create a trigger in the authors table of the pubs database.
Once the authors table is added or deleted, the trigger automatically modifies the file myfile. xml.
Once the myfile. xml file changes, txt2cache is automatically deleted by the system.
Create trigger tr_authors
On authors
For insert, update, delete
As
Declare @ cmd nvarchar (4000)
Select @ cmd = 'bcp "select convert (nvarchar (30), getdate (), 13)" queryout
D: \ cache \ webcache \ myfile. XML-C-sglc2403-USA-p'
Exec master .. xp_mongoshell @ cmd
Go
Private void querybutton_click (Object sender, system. eventargs E)
{
If (Cache ["txt2"]! = NULL)
{
Response. Write ("exists ");
}
Else
{
Response. Write ("not exists ");
}
}
First, click the button to display that cache ["txt2"] exists.
Now we can modify any data in the table authors and click the button to show that cache ["txt2"] does not exist.
We associate the cache with a file. We can also associate the cache with a file group to establish dependencies.
In the following example, we associate the cache with two files (myfile. XML, myfile1.xml). Once any file in the file group changes, CAC
He will delete the data of the "txt2" item from the cache
String [] filepath = new string [] {mappath ("myfile. xml"), mappath ("myfile1.xml ")};
System. Web. caching. cachedependency cachedependencyxmlfile = new
System. Web. caching. cachedependency (filepath );
String cachevaule = "";
Cache. insert ("txt2", cachevaule, cachedependencyxmlfile );
Cache dependencies can be files or keys of other objects
The following code indicates that cache ["txt2"] depends on both the file myfile. XML and the cache ["TXT "].
The cache ["txt2"] will be cleared.
Cache ["TXT"] = "B ";
String [] filepath = new string [] {mappath ("myfile. xml ")};
String [] dependencykey = new string [] {"TXT "};
Sqlconnection con = new sqlconnection ("uid = sa; database = pubs ;");
Sqldataadapter da = new sqldataadapter ("select * from authors", con );
Dataset DS = new dataset ();
Da. Fill (DS );
System. Web. caching. cachedependency cachedependencyxmlfile =
New system. Web. caching. cachedependency (filepath, dependencykey );
Cache. insert ("txt2", DS, cachedependencyxmlfile );
Cache absolute expiration
Cache ["txt3"] automatically expires after 1 hour
Datetime absoluteexpiration = datetime. Now. addhours (1 );
Cache. insert ("txt3", "AA", null, absoluteexpiration, system. Web. caching. cache. noslidingexpiratio
N );
Cache relative (sliding) Expiration
Note: If the created auto scaling expiration time is less than zero or greater than one year, an exception is thrown.
Cache ["txt4"] automatically expires one hour after the last access
Timespan slidingexpiration = timespan. fromhours (1 );
Cache. insert ("txt4", "4", null, system. Web. caching. cache. noabsoluteexpiration, slidingexpiration
);
Cache item priority
When the web server that hosts ASP. NET Applications lacks memory, the cache will selectively clear items to release the system memory. When easing
When adding an item, you can assign it a relative priority compared to other items stored in the cache. When the server processes a large number of requests
Items with a higher priority value are less likely to be deleted from the cache, while items with a lower priority value are more likely to be deleted.
Represented by cacheitempriority enumeration. The default value is normal.
Cache ["txt5"] Priority is set to the highest level. When the server releases the system memory, this cache item cannot be deleted.
Cache. insert ("txt5", "5", null,
System. Web. caching. cache. noabsoluteexpiration,
System. Web. caching. cache. noslidingexpiration,
System. Web. caching. cacheitempriority. High, null );
Callback Method for notifying applications when caching items
ASP. NET provides cacheitemremovedcallback delegation. It defines the signature used to write the event processing program, and when deleted from the cache
In addition, the event handler will respond.
Static system. Web. caching. cacheitemremovedreason reason;
System. Web. caching. cacheitemremovedcallback onremove = NULL;
Public void removedcallback (string K, object v, system. Web. caching. cacheitemremovedreason R)
{
Itemremoved = true;
Reason = R;
}
Onremove = new system. Web. caching. cacheitemremovedcallback (this. removedcallback );
Cache. insert ("TXT", DS, null,
System. Web. caching. cache. noabsoluteexpiration,
System. Web. caching. cache. noslidingexpiration,
System. Web. caching. cacheitempriority. Default, onremove );
The removedcallback method will be called when the cache is removed for any reason