Preface
As we all know, in order to improve the website access performance, various large websites use some caches to improve the application performance. The most commonly used method is to generate HTML pages. In a sense, it can be included in the file cache. However, this method has some drawbacks (for me). Without a complete HTML file management mechanism, a large number of HTMLCodeManagement is a headache.
Let's talk about another common and simple method today, that is, the output cache of ASP. NET.Outputcache
Outputcache
For web development Neter, it is assumed that outputcache will not be unfamiliar. In webform, we include outputcache settings at the top of the ASPX page: <% @ outputcache varybyparam = "NONE" Duration = "10" %> in ASP. in. Net MVC, we add this attribute to the Controller/Action to cache data for improvement.ProgramPerformance:
Public Class Homecontroller: controller { Public Actionresult index () {viewbag. Message =" Welcome to ASP. net mvc! " ; Return View ();} [outputcache (Duration = 10 , Varybyparam = " None " )] Public Actionresult about (){ Return View ();}}
Disadvantages of outputcache
So what are the disadvantages of outputcache? We all know that the outputcache output cache is stored in the memory, that is to say, this practice has been limited to be used only in small websites, Because if our website contains a large number of memory-based caches, i'm afraid it will consume a lot of host memory.
Outputcache is complete
In view of the memory-based storage problem of outputcache, we need to extend outputcache to solve this problem. in net framework 4, outputcacheprovider. With outputcacheprovider, we can have multiple options to create our own cache. In this section, I will expand the outputcache to create a custom file cache.
Use outputcacheprovider to expand outputcache to create a custom File Cache
Create class: filecacheprovider, introduce using system. Web. caching; namespace, inherit from outputcacheprovider abstract class, rewrite four methods:
Add method to insert a specified item into the output cache.
The get method returns a reference to a specified item in the output cache.
Remove Method to remove a specified item from the output cache.
The Set Method inserts a specified item into the output cache. If the item has been cached, the item is overwritten.
Public Class Filecacheprovider: outputcacheprovider { Public String Cachepath { Get ; Set ;} Private String Convertkeytopath ( String Key ){ String File = key. Replace ( ' / ' , ' - ' ); File + = " . Txt " ; Return Path. Combine (cachepath, file );} Public Override Void Initialize ( String Name, system. Collections. Specialized. namevaluecollection config ){ Base . Initialize (name, config ); // Read Cachepath = httpcontext. Current. server. mappath (config [ " Cachepath " ]);} Public Override Object Add ( String Key, Object Entry, datetime utcexpiry ){ Object OBJ = Get (key ); If (OBJ! = Null ){ Return OBJ;} set (Key, entry, utcexpiry ); Return Entry ;} Public Override Object Get ( String Key ){ String Path = Convertkeytopath (key ); If (! File. exists (PATH )){ Return Null ;} Cacheitem item = Null ; Using (Filestream file = File. openread (PATH )){ VaR Formatter = New Binaryformatter (); item = (Cacheitem) formatter. deserialize (File );} If (Item. expirydate <= Datetime. Now. touniversaltime ()){ // Log Remove (key ); Return Null ;} Return Item. item ;} Public Override Void Set ( String Key, Object Entry, datetime utcexpiry) {cacheitem item = New Cacheitem (entry, utcexpiry ); String Path = Convertkeytopath (key ); Using (Filestream file = File. openwrite (PATH) {binaryformatter formatter =New Binaryformatter (); formatter. serialize (file, item );}} Public Override Void Remove ( String Key ){ String Path = Convertkeytopath (key ); If (File. exists (PATH) {file. Delete (PATH) ;}} [serializable] Public Class Cacheitem { Public Datetime expirydate; Public Object Item; Public Cacheitem ( Object Entry, datetime utcexpiry) {item = Entry; expirydate = Utcexpiry ;}}
In the instance program, I put the cache in the cachepath directory configured in the config file. For details, see the initialize method.
Configuration File
You need to configure the cache handler driver in the web. config file.
< System. Web > < Caching > < Outputcache Defaultprovider = "Filecache" > < Providers > < Add Name = "Filecache" Type = "Filecache. provider. filecacheprovider" Cachepath = "~ /Cache" /> </ Providers > </ Outputcache > </ Caching >
How to use it?
After the above configuration, it is easy to use, because it is an extension of ASP. NET output cache outputcache, so the usage is the same as the previous usage. I use the following in MVC:
Namespace Filecache. controllers { Public Class Homecontroller: controller { Public Actionresult index () {viewbag. Message = " Welcome to ASP. net mvc! " ; Return View ();} [outputcache (Duration = 10 , Varybyparam = " None " )] Public Actionresult about (){ Return View ();}}}
As you can see, I marked [outputcache (duration = 10, varybyparam = "NONE")] on the about action, set the cache time to 10 minutes, and do not cache it again based on any parameters, run. You can view the cached file under the configured cache file:
After running the program, visit the about page and you will see that a cache file is generated in the cache folder.
Notes
I created the cache folder in advance in the project. Of course, the folder name can be obtained at will, just in the web. the Config ing is correct. If an error occurs during running, it may be because the folder does not exist, or you can check whether the cache folder exists in the cache expansion code. If not, the program can be created.
Legacy problems
We can see that the cached file is saved as TXT text. Can we save the cached file as an XML file? If XML is used, you can further modify and use generic classes to solve the XML serialization problem of different objects. If you have better suggestions, you may wish to raise them.