One of my Favorite feature of ASP.NET 4.0 is that we can offload the ouputcache from in-Process memory to external storage. i.e Disk, or a big in-memory cache. then we can Cache more Data instead of being flushed out of memory when asp.net worker process get a lot pressure. this will be more helpful during the holidays season.
Coherence is one popular in-memory distributed cache cluster. I just spent 30 minutes to build one simple outputcache provider. less than 100 lines of Code. much easier than the diskcache example:)
- Keep the object in-memory, we need take care the object serialization /deserialization
- this can be done easily in .NET. there are 5+ different serializer/formatters
- I will use the BinaryFormatter which is more space -efficient
- every cache item has a expiry setting, need flush and purge it when it reaches lifetime settings.
- Coherence has the overflow setting,
- you can specify the ttl when inserting object into the cache.
- Setup your distributed Cache Cluster and one dedicated cache.
- Reference Coherence Assembly and fill up 4 methods which are required by OutputCacheProvider
- Config asp.net web.config, point the provider to ours.
Setup your distributed Cache Cluster and one dedicated cache. here I will define one cache called outputcache to hold all the cached data.
Build the CoherencCacheOutputCacheProvider.
- Create one Class library project named CoherencCacheOutputCacheProviderLib
- reference several dlls.
- System.web.dll (where OutputCacheProdiver exists)
- Create one Class named CoherencCacheOutputCacheProvider
- here is the source code. you may just copy and paste .
change your asp.net application to using the New cache provider.
- reference the dll we just compiled
- change the web.config
- tune you outputcache settings.
here is the web.config
testing and make sure cache works as it should be.
first, I create one simple page just pringout the current time, enable the outputcache and setup duration to 30 seconds. and very by url parameter x
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="testcache.aspx.cs" Inherits="testcache" %>
<%@ OutputCache Duration="30" VaryByParam="x" %>
Last Update :<% =System.DateTime.Now %>
When I browse http://localhost:39847/WebSite1/testcache.aspx?x=1
when try different x value, will get more cached object.
the key for the item is url+xvalue.
Let me change the cache logic to vary by browser.
<%@ OutputCache Duration="30" VaryByParam="none" VaryByHeader="user-agent" %>
Since we config the cache expiry setting to 30 seconds. so let’s verify the cache item are gone once they get expired.
asp.net 4.0 provider model is very convenient for extension. OutputCacheProvider comes to a citizen of the provervider model.
just like the coherence session provider for asp.net, it’s plug and play. write once , and enjoy the benefit everywhere.