CacheUtil.Cache cache = CacheUtil.newInstance("question",7*24*60*60);
if(!AssertUtil.isEmpty(cache.get("activityInfoVO"))) {
activityInfoVO=cache.get("activityInfoVO");
logger.info("缓存读取大转盘信息成功");
}else{
activityInfoVO= activityService.getActivityByType("1");
cache.set("activityInfoVO",activityInfoVO);
logger.info("缓存中没大转盘信息去数据库读并保存入缓存");
}
package cn.com.do1.component.util.cached;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import net.rubyeye.xmemcached.MemcachedClient;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
/**
* Copyright © 2011 广州市道一信息技术有限公司<br />
* All rights reserved.<br />
*
* @author 施华 Anders See
* @version 1.0
* @since 2011-03-14
*/
public class CacheUtil {
private transient final static Logger log = Logger.getLogger(CacheUtil.class);
private final static Map<String, Cache> weakMap = Collections.synchronizedMap(new WeakHashMap<String, Cache>());
private static MemcachedClient client;
private static Integer defaultExpMinutes = 60;
public void setClient(MemcachedClient client) {
CacheUtil.client = client;
}
public synchronized void setDefaultExpMinutes(Integer exp) {
defaultExpMinutes = exp;
}
public static Cache newInstance(String keyPrefix) {
return newInstance(keyPrefix, defaultExpMinutes);
}
public static Cache newInstance(String keyPrefix,int expSecond) {
if (StringUtils.isBlank(keyPrefix)) {
keyPrefix = "default";
}
Cache cache = weakMap.get(keyPrefix);
if (null == cache) {
weakMap.put(keyPrefix, cache = new Cache(keyPrefix, expSecond));
}
return cache;
}
public static class Cache {
private String keyPrefix;
private Integer exp;
private Cache(String keyPrefix, Integer exp) {
this.keyPrefix = keyPrefix + "_";
this.exp = exp;
}
public boolean set(final String key, final int expSec, final Object notNullValue) {
try {
return client.set(keyPrefix + key, expSec, notNullValue);
} catch (Exception e) {
log.error(e.getMessage(), e);
return false;
}
}
public boolean set(final String key, final Object notNullValue) {
return this.set(key, this.exp, notNullValue);
}
public boolean set(final Number key, final Object notNullValue) {
return this.set(String.valueOf(key.longValue()), notNullValue);
}
public <T> T get(final String key) {
try {
return client.get(keyPrefix + key);
} catch (Exception e) {
log.error(e.getMessage(), e);
return null;
}
}
public void deleteWithNoReply(final String key) {
try {
client.deleteWithNoReply(keyPrefix + key);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
}