Wednesday, November 20, 2013

Memcached in MVC projects

1. Install Memcached server in Windows

The latest Memcached version is 1.4.5, but the application doesn't support "-d install" parameter to install itself as Windows service.

So right now the 1.4.4 is still the option to go under Windows. Get a package from memcached 1.4.4 for Windows 32-bit from http://downloads.northscale.com/memcached-win32-1.4.4-14.zip.

Unzipped to a folder, then run the following command to install as win services
memcached.exe -d install

Start the server from the Microsoft Management Console or by running one of the following commands:
memcached.exe -d start

2. Check Memcached installation

You can telnet to the default port 11211 to check the status:
telnel localhost 11211

Then use the command stats to check status
stats
flush_all

3. Enyim Memcached client

EnyimMemcached is a .NET client library for memcached written in C#. You can get the source code from https://github.com/enyim/EnyimMemcached

Then it's simple to use the cache:

private static IMemcachedClient _cache = new MemcachedClient();

_cache.Store(StoreMode.Set, key, value);

object r = _cache.Get(key);
Of course you need some setting in the app/web.config:


  
    
      
You don't need log section if you are not doing the detail logging. Also the transcoder section is added here because I'm using the DataContractSerializer for my entities.

4. Some notes

On Azure, window only support the default protocol (Text).
 
The Enyim source code getting from Github is using log4net 1.2.10.0 targeting at .Net framework 3.5. If you are using log4net 1.2.12.0 (targeting at .Net framework 4.0) then there are some dll binding issue.

In order to re-compile the project to reference log4net 1.2.12.0 and targeting .Net framework 4.0, I end up disable the sign and removing the strong name sign public key file public_key.snk from the project, also remove the reference part in the CommonProperties.targets file under build folder.