MemcachedClient provides
following method to delete a key from Memcached.
public
OperationFuture<Boolean> delete(String key)
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.CASValue; 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 = "Tutorial"; 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")); System.out.println("\nDeleting the key 12345\n"); memClient.delete("12345"); 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 Tutorial Deleting the key 12345 Value of the key 12345 is null
No comments:
Post a Comment