Outsource your caching with memcached
I'm currently working on a large business system for a client where there are several caching situations, because the service that delivers the data is too slow, the database is too slow or we don't want to hit the source for the data all too often. I've been hand rolling most of these cache layers myself. I don't like the idea of using ASP.NET caching for non ASP.NET applications.
Memcached
Always when I hit the same problem the third time, I start looking for a common solution. When I was about to write my third caching implementation, I made a google search and found out that I probably should move the cache outside the application pool into a seperate service. Memcached is a service that I've heard of before, but I haven't really tried it out. Memcached is
- a key/value store
- hip and cool because it's NoSQL
- available as a windows service from NorthScale with a simple .NET client API
How does it work?
Download and install the service from NorthScale. You'll get a user interface where you can analyze status of your cache service. Notice all the stuff about clustering which is cool, but probably only usable if you're Facebook or Twitter.
Before you start writing code you should create a bucket, where you want to store your data. If I understood this correctly, buckets are just there to separate one type of cached data from another type of cached data.
Your own project
Add references to the Enyim.Caching.dll
and Northscale.Store.dll
.
You will need to add configuration to tell NorthScaleClient where to find memcached service.
Now you can get and set data from the cache like this.
// Get data from key, returns null if key is not set in cache
var result = cache.Get<string>(key);
if (result == null)
{
// Since cache did not exist, get from real source
result = service.GetData();
// Input data found to cache
// Add result to cache (will not overwrite any value)
// "key" - the key to store it under
// "result" - the value to store
// TimeSpan.FromDays(1) - let it expire in 24 hours
cache.Store(StoreMode.Add, key, result, TimeSpan.FromDays(1));
}
return result;
}
Easy huh! Now, go out there and cache the world!