Sunday, August 15, 2010

? Memcached and Java

1. Start the Memcache
$memcached -d -m 512 127.0.0.1 -p 1121


2. Check Memcache by Telnet  
$ telnet localhost 11211
Trying ::1...
Connected to localhost.
Escape character is '^]'.
get customer
END
set customer 0 3600 10  
complexity
STORED
get customer
VALUE customer 0 10
complexity
END


quit


Out of the various Java Memcached clients, I prefer to use Dustin's Spymemcached client.


Complete Spymemcached list of JAVA api is available here.




Sample code on how to create a connection:



MemcachedClient c=new MemcachedClient(
                new InetSocketAddress("hostname", portNum));

        // Store a value (async) for one hour
        c.set("someKey", 3600, someObject);
        // Retrieve a value.
        Object myObject=c.get("someKey");





                               OR





// Get a memcached client connected to several servers
      // over the binary protocol
      MemcachedClient c = new MemcachedClient(new BinaryConnectionFactory(),
              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 f = c.asyncGet("someKey");       try {           myObj = f.get(5, TimeUnit.SECONDS);       // throws expecting InterruptedException, ExecutionException       // or TimeoutException       } catch (Exception 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.  It is okay to cancel it if running.           f.cancel(true);           // Do other timeout related stuff       }








No comments:

Post a Comment