Introduction:
This article is targeted to be a tutorial of how to use Memcached caching server in .net, as well as a reflection of Microsoft’s asp .net’s caching techniques.
Caching – the Old Picture:
It took a long time for me to realize that the Caching services provided by Microsoft till .Net 2 are actually not worth at all. Even now, I simply fail to understand what certain features really do as value-add.
For example Microsoft had some 3 types of caching
- Page output caching – We can have different types of parameters and have one cached page each
- Fragment caching – Small fragments of pages can be cached like User Controls etc.,
- Application Level caching – Some data being stored in memory
To me (being frank), this was told to small kids like me when I started some programming. The real world scenario of a cache comes in situations like some of the below.
I have 1000s of users who keep querying data, for example like trading company scrip names, for future scripts we need to supply information on contract start/expiry etc,. This information is always needed in any normal application. For example, even for an online grocery store I can keep serving the item name, its description, price etc., for a few hours as this information do not change very frequently. We are not talking about millions, but for even thousands of visitors a carefully planned caching strategy gives a great boost in website performance.
Caching – A Better Picture:
I welcome the comments and retort from people on my opinions. But in my view Memcached is a far superior caching server. Please note the word “Server” here. This is not something which goes as part of asp .net server but stays as an external process and can run as a service. Anyways the scope of the article is to give a simple insight of how to use memcached client in asp .net (and we can extend the same idea to any other C# applications as well)
Memcached:
“A Free & open source, high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load”. It is originally built for linux (which is a cost effective OS), but now there are some servers built on windows. One from Couchbase and the other as a freesource from http://code.jellycan.com/memcached/. Infact I could not find a download link for the server even from the above link. So I have attached the one I am using for your easier reference in this article Memcached Download link.
Infact the easiest and the best server for memcached would be from the original linux version available at http://memcached.org/ and it is generally suggested to use linux memcached for production environments. Otherwise we can opt for the couchbase server as well as mentioned above.
Installing MemCached:
We’ll target to use this in an asp .net MVC application with C# as or language. As on date Visual Studio 2012 is popular so we’ll try and use the same..
- Start the memcached service from the “Windows Service Manager” console
- Open Visual Studio 2012 and create a new asp .net MVC application.
- To use the memcached client we need to add the client libraries with enyim caching client and a caching provider. I generally use enyim client and found to be working neatly in production environments. You can download the enyim client from enyim github and build from source. But for ease of use, I have attached them to this article by clicking Memcached Dependency Files . Please note that the dependency library MemcacheProvider also requires log4net, which is also attached in the zip file.
- Attach the library files MemcachedProviders.dll and Enyim.Caching.dll to the project as references.
- Code snippet for setting and getting the cache values
- Add using MemcachedProviders.Cache for getting all provider classes for CacheProvider.
- Set Values into cache.
String key = "1"; String value = "Test data which can be stored. Even serialized xml or json strings can be stored and retrieved later"; bool cached = DistCache.Add(key, value); if (!cached) throw new Exception(String.Format("{0} - Failed to cached object with key {1}, Check if the object is serializable", System.DateTime.Now, key));
- Get value from cache
Object objvalue= (Object)DistCache.Get(key); String value = objvalue.ToString();
- Remove the value from cache
DistCache.Remove(key);
- Add an entry under configSections.
<section name="cacheProvider" type="MemcachedProviders.Cache.CacheProviderSection, MemcachedProviders" allowDefinition="MachineToApplication" restartOnExternalChanges="true" /> <sectionGroup name="enyim.com"> <section name="memcached" type="Enyim.Caching.Configuration.MemcachedClientSection, Enyim.Caching" /> </sectionGroup>
- Add the following lines in web.config.
<enyim.com> <memcached> <servers> <!-- put your own server(s) here--> <add address="127.0.0.1" port="11211" /> </servers> <socketPool minPoolSize="10" maxPoolSize="100" connectionTimeout="00:00:10" deadTimeout="00:02:00" /> </memcached> </enyim.com> <cacheProvider defaultProvider="MemcachedCacheProvider"> <providers> <add name="MemcachedCacheProvider" type="MemcachedProviders.Cache.MemcachedCacheProvider, MemcachedProviders" keySuffix="_sample" defaultExpireTime="2000" /> </providers> </cacheProvider>
The above sample assumes that we have the memcache server installed on our local machine at port 11211, which is default. If we have a different installation, the config can point to such specific configuration.
The final output of the screen looks like this.
Attachments:
Click here to download the Example Project.
Click here to download the dependency files