Skip to content
This repository has been archived by the owner on Jul 7, 2019. It is now read-only.

MemcachedClient Usage

robertmircea edited this page Feb 22, 2011 · 3 revisions
    MemcachedClient client = new MemcachedClient(configuration);

The configuration can come either from app.config or can be a custom IMemcachedClientConfiguration implementation.

If the default configuration section (enyim.com/memcached) exists in the app.config, we can just do

    MemcachedClient client = new MemcachedClient();

This will create the server pool, initialize the sockets, and the client is ready to roll:

    client.Set(StoreMode.Set, "Test", "Hello World");

Important! MemcachedClient is a "heavy object", as in creating and initializing the client is quite expensive. (It has a socket pool inside, needs to calculate the tables for the consistent hashing, etc.) So, DO NOT create a client every time you want to perform an operation (well, you can, but 1) you need to Dispose() it after you finished, and 2) this will slow down your application considerably).

Do not do this:

Never create a client multiple times. Or if you have a very good reason, at least use the using(...){ } construct to release the resources.

    private Profile GetProfile(string user)
    {
    	MemcachedClient client = new MemcachedClient();
    	Profile p = client.Get(user) as Profile;

    	if (p == null) 
    		....
    }

This is how you should do it:

Create the cache as early as possible while your application is initializing, then share the instances amongst as many parts/modules as you can. Most applications have a cache layer, this is a good candidate for doing the initialization and for exposing it to the other parts of the application.

    public static MemcachedClient ProfileCache;
    public static MemcachedClient OtherCache;

    public void AppInit()
    {
    	ProfileCache = new MemcachedClient("foo/bar");
    	OtherCache = new MemcachedClient("foo/bar2"); // connect to a different server pool
    }

    private Profile GetProfile(string user)
    {
    	Profile p = ProfileCache.Get(user) as Profile;
    
    	if (p == null) 
    		....
    }