ASP. NET performance optimization-Build Custom File Cache

Source: Internet
Author: User

Now, with OutputCacheProvider in. NET4.0, we can choose to create our own cache. For example, we can store the HTML output cache to the memcached distributed cluster server, or MongoDB (a common document-oriented database, you may wish to read this http://msdn.microsoft.com/zh-cn/magazine/gg650661.aspx ). Of course, we can also store the cache as a file on the hard disk. Considering the scalability, this is the cheapest practice. This article describes how to build a custom file cache.

1: OutputCacheProvider

OutputCacheProvider is an abstract base class. We need four methods in override, which are:

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.

2: Create your own File Cache processing class

This type is FileCacheProvider, and the code is as follows:

Copy codeThe Code is as follows: public class FileCacheProvider: OutputCacheProvider
{
Private static readonly ILog log = LogManager. GetLogger (System. Reflection. MethodBase. GetCurrentMethod (). DeclaringType );
Public override void Initialize (string name, NameValueCollection attributes)
{
Base. Initialize (name, attributes );
CachePath = HttpContext. Current. Server. MapPath (attributes ["cachePath"]);
}
Public override object Add (string key, object entry, DateTime utcExpiry)
{
Object obj = Get (key );
If (obj! = Null) // this step is important
{
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. Info (item. ExpiryDate + "*" + key );
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 );
}
Public string CachePath
{
Get;
Set;
}
Private string ConvertKeyToPath (string key)
{
String file = key. Replace ('/','-');
File + = ". txt ";
Return Path. Combine (CachePath, file );
}
}
[Serializable]
Public class CacheItem
{
Public DateTime ExpiryDate;
Public object Item;
Public CacheItem (object entry, DateTime utcExpiry)
{
Item = entry;
ExpiryDate = utcExpiry;
}
}

There are two areas to note:
In the Add method, there is a condition judgment and such processing must be done. Otherwise, the cache mechanism will cache the first result. After the validity period expires, the cache will become invalid and will not be rebuilt;
In the example program, we simply put the Cache to the Cache directory. In actual project practice, considering that there will be thousands of cached pages, we must grade the directory, otherwise, searching for and reading cached files will become an efficiency bottleneck, which will exhaust the CPU.
3: Configuration File
We need to configure the cache handler in Web. config as a custom FileCacheProvider, that is, add a node under <system. web>:Copy codeThe Code is as follows: <caching>
<OutputCache defaultProvider = "FileCache">
<Providers>
<Add name = "FileCache" type = "MvcApplication2.Common. FileCacheProvider" cachePath = "~ /Cache "/>
</Providers>
</OutputCache>
</Caching>

4: Cache Usage
We assume that it is used in MVC control (if you want to use it in ASP. NET page, the page contains <% @ OutputCache VaryByParam = "none" Duration = "10" %>), you can see that the Index is not output in the cache, index2 caches the output, and the cache time is 10 seconds.Copy codeThe Code is as follows: public class HomeController: Controller
{
Private static readonly ILog log = LogManager. GetLogger (System. Reflection. MethodBase. GetCurrentMethod (). DeclaringType );
Static string s_conn = "Data Source = 192.168.0.77; Initial Catalog = luminjidb; User Id = sa; Password = sa ;";
Public ActionResult Index ()
{
Using (DataSet ds = Common. sqlHelper. executeDataset (s_conn, CommandType. text, "select top 1 * from NameTb a, DepTb B where. depID = B. id order by newid ()"))
{
ViewBag. Message = ds. Tables [0]. Rows [0] ["name"]. ToString ();
}
Return View ();
}
[OutputCache (Duration = 10, VaryByParam = "none")]
Public ActionResult Index2 ()
{
Using (DataSet ds = Common. sqlHelper. executeDataset (s_conn, CommandType. text, "select top 1 * from NameTb a, DepTb B where. depID = B. id order by newid ()"))
{
ViewBag. Message = ds. Tables [0]. Rows [0] ["name"]. ToString ();
}
Return View ();
}
}

5: view the effect

The above code generates a Cache file in the Cache folder after Index2 is accessed, as follows:

Now, we start to evaluate the performance comparison between the output cache and the NO output cache, and simulate 100 concurrent requests of 1000 users as follows:

As you can see, after the output cache is available, the throughput is significantly increased by 10 times.

6. Download Code

The original code of FileCacheProvider comes from the network. I modified the BUG and downloaded all the Code as follows: mvcapplication20120110907.rar

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.