Wednesday 24 August 2016

Spymemcached: set data

Following step-by-step procedure explains how to set data to cache.

Step 1: Get MemcachedClient instance. It is a client to a memcached server. Following statement is used to define MemcachedClient.

MemcachedClient client = new MemcachedClient(new InetSocketAddress(hostname, portNum));

Step 2: Once you got the MemcachedClient instance, you can able to write data to server and read data from server. Spymemcached provides following method to set data to server.

OperationFuture<Boolean> set(String key, int exp, Object o)
Above method set an object in the cache. ‘exp’ is the expiry time of the object in seconds, this number of seconds may not exceed 60*60*24*30 (number of seconds in 30 days).

Step 3: After that, you can call the get method of MemcachedClient instance to get the data associated with given key.

public Object get(String key)
Above method return an object associated with given key. If the key don’t exist in memcached server, then it return null.


Following is the complete working application.
package com.sampe.cache;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import net.spy.memcached.MemcachedClient;

/**
 * Utility class to create client.
 * 
 * @author harikrishna_gurram
 *
 */
public class CacheClientUtil {

 private static MemcachedClient client = null;
 private static Logger logger = LogManager.getLogger();

 public static Optional<MemcachedClient> getClient(InetSocketAddress addr) {
  if (Objects.isNull(addr)) {
   logger.error("getClient: addr shouldn't be null");
   return Optional.empty();
  }

  try {
   client = new MemcachedClient(addr);
  } catch (IOException e) {
   logger.error(e);
   return Optional.empty();
  }

  return Optional.of(client);
 }

 public static Optional<MemcachedClient> getClient(List<InetSocketAddress> addrs) {
  if (Objects.isNull(addrs)) {
   logger.error("getClient: addrs shouldn't be null");
   return Optional.empty();
  }

  try {
   client = new MemcachedClient(addrs);
  } catch (IOException e) {
   logger.error(e);
   return Optional.empty();
  }

  return Optional.of(client);
 }

 public static void shutdownClient(MemcachedClient client) {
  if (Objects.isNull(client)) {
   logger.error("shutdownClient: client object is already closed");
   return;
  }

  client.shutdown();
 }
}

package com.sampe.cache;

import java.net.InetSocketAddress;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import net.spy.memcached.MemcachedClient;

public class Test {
 private static Logger logger = LogManager.getLogger();

 public static void main(String args[]) throws InterruptedException, ExecutionException {
  /* Get MemcachedClient */
  InetSocketAddress address = new InetSocketAddress("127.0.0.1", 11211);

  Optional<MemcachedClient> client = CacheClientUtil.getClient(address);

  if (!client.isPresent()) {
   logger.error("Unable to create client instance");
   return;
  }

  MemcachedClient memClient = client.get();

  /* Set some data */
  String data = "{\"org\":[{\"name\":\"Honeywell\",\"yrsOfExperience\":2.2},{\"name\":\"IBM\",\"yrsOfExperience\":1.8}],\"firstName\":\"Krishna\",\"lastName\":\"Hari\",\"salary\":80000.0}\r\n";

  Future<Boolean> future = memClient.set("12345", 900, data);

  System.out.println("set status:" + future.get());

  System.out.println("Value of the key 12345 is " + memClient.get("12345"));

  CacheClientUtil.shutdownClient(memClient);

 }
}


Output
set status:true
Value of the key 12345 is {"org":[{"name":"Honeywell","yrsOfExperience":2.2},{"name":"IBM","yrsOfExperience":1.8}],"firstName":"Krishna","lastName":"Hari","salary":80000.0}


You can manually verify by using telnet command utility like below.

$ telnet 127.0.0.1 11211
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
get 12345
VALUE 12345 0 148
{"org":[{"name":"Honeywell","yrsOfExperience":2.2},{"name":"IBM","yrsOfExperience":1.8}],"firstName":"Krishna","lastName":"Hari","salary":80000.0}

END


Previous                                                 Next                                                 Home

No comments:

Post a Comment