com.njmd.framework.utils.memcached.SpyMemcachedClient.java Source code

Java tutorial

Introduction

Here is the source code for com.njmd.framework.utils.memcached.SpyMemcachedClient.java

Source

/**
 * Copyright (c) 2005-2012 springside.org.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.njmd.framework.utils.memcached;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import net.spy.memcached.MemcachedClient;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;

/**
 * SpyMemcached Client?,??Get/GetBulk/Set/Delete/Incr/Decr?.
 * 
 * ????getClient()?SpyMemcachedClient?.
 * 
 * @author calvin
 */
public class SpyMemcachedClient implements DisposableBean {

    private static Logger logger = LoggerFactory.getLogger(SpyMemcachedClient.class);

    private MemcachedClient memcachedClient;

    private long shutdownTimeout = 1000;

    /**
     * Get, ??, Null.
     */
    @SuppressWarnings("unchecked")
    public <T> T get(String key) {
        try {
            return (T) memcachedClient.get(key);
        } catch (RuntimeException e) {
            handleException(e, key);
            return null;
        }
    }

    /**
     * ??KeyskeyPrefix
     * 
     * @param <T>
     * @param keys
     * @param keyPrefix
     * @return
     */
    public <T> Map<String, T> getBulk(String[] keyArray, String keyPrefix) {
        try {
            List<String> keyList = new ArrayList<String>();
            for (String key : keyArray) {
                keyList.add(keyPrefix + key);
            }
            return (Map<String, T>) memcachedClient.getBulk(keyList);
        } catch (RuntimeException e) {
            handleException(e, StringUtils.join(keyArray, ","));
            return null;
        }
    }

    /**
     * GetBulk, ??.
     */
    @SuppressWarnings("unchecked")
    public <T> Map<String, T> getBulk(Collection<String> keys) {
        try {
            return (Map<String, T>) memcachedClient.getBulk(keys);
        } catch (RuntimeException e) {
            handleException(e, StringUtils.join(keys, ","));
            return null;
        }
    }

    /**
     * Set, ?.
     */
    public void set(String key, int expiredTime, Object value) {
        memcachedClient.set(key, expiredTime, value);
    }

    /**
     * Set,1, ?false??.
     */
    public boolean safeSet(String key, Object value, int expiration) {
        Future<Boolean> future = memcachedClient.set(key, expiration, value);
        try {
            return future.get(1, TimeUnit.SECONDS);
        } catch (Exception e) {
            future.cancel(false);
        }
        return false;
    }

    /**
     *  Delete, ?.
     */
    public void delete(String key) {
        memcachedClient.delete(key);
    }

    /**
     * Set,1, ?false??.
     */
    public boolean safeDelete(String key) {
        Future<Boolean> future = memcachedClient.delete(key);
        try {
            return future.get(1, TimeUnit.SECONDS);
        } catch (Exception e) {
            future.cancel(false);
        }
        return false;
    }

    /**
     * Incr.
     */
    public long incr(String key, int by, long defaultValue) {
        return memcachedClient.incr(key, by, defaultValue);
    }

    /**
     * Decr.
     */
    public long decr(String key, int by, long defaultValue) {
        return memcachedClient.decr(key, by, defaultValue);
    }

    /**
     * Incr, ??, key?-1.
     */
    public Future<Long> asyncIncr(String key, int by) {
        return memcachedClient.asyncIncr(key, by);
    }

    /**
     * Decr, ??, key?-1.
     */
    public Future<Long> asyncDecr(String key, int by) {
        return memcachedClient.asyncDecr(key, by);
    }

    private RuntimeException handleException(Exception e, String key) {
        logger.warn("spymemcached client receive an exception with key:" + key, e);
        return new RuntimeException(e);
    }

    @Override
    public void destroy() throws Exception {
        if (memcachedClient != null) {
            memcachedClient.shutdown(shutdownTimeout, TimeUnit.MILLISECONDS);
        }
    }

    public MemcachedClient getMemcachedClient() {
        return memcachedClient;
    }

    public void setMemcachedClient(MemcachedClient memcachedClient) {
        this.memcachedClient = memcachedClient;
    }

    public void setShutdownTimeout(long shutdownTimeout) {
        this.shutdownTimeout = shutdownTimeout;
    }
}