Search This Blog

Wednesday, February 3, 2010

Working with Java Memcached API

Memcached is a memory object caching system. It is used to improve the performance of web applications which is dynamic in nature.  Memcached server is an in-memory key value store for small amount of data like strings, objects from results of database calls, API calls, or page rendering.  It is very simple. Server (daemon) process written in C, providing an in-memory hashmap. Clients can be written in any language.

The below example gives very basic example to understand memcached server. 

Set memcached clinet jar file (memcached-client-2.3.jar) in your classpath.

General Usage:

Use below code to connect with memcache and push object to memcache and retrive object from memcache.

MemcachedClient c = null;
c = new MemcachedClient(new InetSocketAddress("memcached_host_IP", PORT));
c.set("MyTest", 60*60*24, new Integer(20));
int fromMC = (Integer)c.get("MyTest");
} catch (Exception ex){
out.println("Exception raised when getting object from memcached; "+ex.getMessage());
} finally{
if(c != null) c.shutdown();

In the above code below line creates MemcachedClient with memcached ip, and port. It establishes connection to the memcache.

c = new MemcachedClient(new InetSocketAddress("memcached_host_IP", PORT));

The below line is storing Integer object into the memcache with a key "MyTest". You can get the object using this key. The object will be available in memcache for 24 hours.

c.set("MyTest", 60*60*24, new Integer(20));

The below line gets the stored object from memcache by passing key. You need to do proper typecast.

int fromMC = (Integer)c.get("MyTest");

The finally block below closes the memcache client connection.

if(c != null) c.shutdown();

Advaned Usage:

MemcachedClient may be processing a great deal of asynchronous messages or possibly dealing with an unreachable memcached, which may delay processing. If a memcached is disabled, for example, MemcachedConnection will continue to attempt to reconnect and replay pending operations until it comes back up. To prevent this from causing your application to hang, you can use one of the asynchronous mechanisms to time out a request and cancel the operation to the server.

Get a memcached client connected to several servers, over the binary protocol.

MemcachedClient c = new MemcachedClient(new BinaryConnectionFactory(), AddrUtil.getAddresses("server1:11211 server2:11211"));

No comments:

Post a Comment