-
Notifications
You must be signed in to change notification settings - Fork 359
MemcachedClient Usage
MemcachedClientConfiguration configuration= new MemcachedClientConfiguration();
configuration.AddServer("127.0.0.1:11211");
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.Store(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).
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)
....
}
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)
....
}