|
|
Examples
Example usage
Simple Example
MemcachedClient c=new MemcachedClient(
new InetSocketAddress("hostname", portNum));
// Store a value (async) for one hour
c.set("someKey", 3600, someObject);
// Retrieve a value (synchronously).
Object myObject=c.get("someKey");Taking Advantage of Asynchronous Gets
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
MemcachedClient c=new MemcachedClient(
AddrUtil.getAddresses("server1:11211 server2:11211"));
// Try to get a value, for up to 5 seconds, and cancel if it doesn't return
Object myObj=null;
Future<Object> f=c.asyncGet("someKey");
try {
myObj=f.get(5, TimeUnit.SECONDS);
} catch(TimeoutException e) {
// Since we don't need this, go ahead and cancel the operation. This
// is not strictly necessary, but it'll save some work on the server.
f.cancel(false);
// Do other timeout related stuff
}Establishing a Binary Protocol Connection
As of release 2.0, the new binary wire protocol for memcached is supported. Below is an example of how you might connect to a server using the binary protocol:
// Get a memcached client connected to several servers with the binary protocol
MemcachedClient c=new MemcachedClient(
new BinaryConnectionFactory(),
AddrUtil.getAddresses("server1:11212 server2:11212"));
// Proceed to do cool stuff with memcached using the binary protocol.
Sign in to add a comment

The classname should be MemCachedClient?, not MemcachedClient?.