📄 countcacheadvice.java
字号:
/**
*
*/
package com.lily.dap.dao;
import java.io.Serializable;
//import java.lang.reflect.Method;
import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;
import com.lily.dap.model.QueryCondition;
/**
* 对AbstractDaoHibernate的count和executeSQLCount进行缓存
* 缓存时间在WEB-INF\classes\ehcache.properties中定义,默认为5分钟
* 对于大数据量的数据查询,发现在查出的结果数据进行翻页时,都必须做记录合计查询,如果数据很大时速度会很慢,所以对这个合计值进行缓存
*
* @author zouxuemo
*
*/
public class CountCacheAdvice implements MethodInterceptor {
protected final Log logger = LogFactory.getLog(getClass());
protected Cache cache;
/**
* @param cache the cache to set
*/
public void setCache(Cache cache) {
this.cache = cache;
}
/**
* 检查是否提供必要参数。
*/
public void afterPropertiesSet() throws Exception {
Assert.notNull(cache, "A cache is required. Use setCache(Cache) to provide one.");
}
public Object invoke(MethodInvocation invocation) throws Throwable {
String methodName = invocation.getMethod().getName();
Object[] arguments = invocation.getArguments();
Object result;
String cacheKey = getCacheKey(methodName, arguments);
Element element = cache.get(cacheKey);
if (element != null)
logger.debug("look cache for (" + cacheKey + "), find value [" + element.getValue() + "].");
else
logger.debug("look cache for (" + cacheKey + "), not find value.");
if (element == null) {
result = invocation.proceed();
logger.debug("put value [" + result + "] to cache (" + cacheKey + ").");
element = new Element(cacheKey, (Serializable)result);
cache.put(element);
}
return element.getValue();
}
private String getCacheKey(String methodName, Object[] arguments) {
StringBuffer sb = new StringBuffer();
sb.append(methodName);
if ("count".equals(methodName)) {
Class clazz = (Class)arguments[0];
QueryCondition queryCondition = (QueryCondition)arguments[1];
sb.append(".").append(clazz.getName());
sb.append("[").append(queryCondition.getConditions()).append("]");
} else if ("executeSQLCount".equals(methodName)) {
String sql = (String)arguments[0];
sb.append(".[").append(sql).append("]");
} else if ((arguments != null) && (arguments.length != 0)) {
for (int i=0; i<arguments.length; i++) {
sb.append(".").append(arguments[i]);
}
}
return sb.toString();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -