首页>代码>s2sh权限管理实例>/frame/src/org/frame/ehcache/MethodCacheInterceptor.java
package org.frame.ehcache;

import java.io.Serializable;

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.beans.factory.InitializingBean;
import org.springframework.util.Assert;

/**
* @Description : 描述
* @author liuq
*/
public class MethodCacheInterceptor implements MethodInterceptor,
		InitializingBean {
	private static final Log logger = LogFactory
			.getLog(MethodCacheInterceptor.class);

	private Cache cache;

	public void setCache(Cache cache) {
		this.cache = cache;
	}

	public MethodCacheInterceptor() {
		super();
	}

	public Object invoke(MethodInvocation invocation) throws Throwable {

		String targetName = invocation.getThis().getClass().getName();
		System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>intercept class : " + targetName);

		String methodName = invocation.getMethod().getName();
		Object[] args = invocation.getArguments();
		System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>intercept method : " + methodName+ " || args : " +args);

		Object[] arguments = invocation.getArguments();
		Object result;

		logger.debug("Find object from cache is " + cache.getName());

		String cacheKey = getCacheKey(targetName, methodName, arguments);
		Element element = cache.get(cacheKey);

		if (element == null) {
			logger.debug("Hold up method , Get method result and create cache........!");
			result = invocation.proceed();
			element = new Element(cacheKey, (Serializable) result);
			cache.put(element);
		} 
		return element.getValue();
	}

	private String getCacheKey(String targetName, String methodName,Object[] arguments) {
		StringBuffer sb = new StringBuffer();
		sb.append(targetName).append(".").append(methodName);
		if ((arguments != null) && (arguments.length != 0)) {
			for (int i = 0; i < arguments.length; i++) {
				sb.append(".").append(arguments[i]);
			}
		}
		return sb.toString();
	}

	public void afterPropertiesSet() throws Exception {
		Assert.notNull(cache,"Need a cache. Please use setCache(Cache) create it.");
	}

}
最近下载更多
kong.yee  LV40 2020年7月5日
adolph_jiang  LV11 2020年4月28日
gwt爱学习  LV16 2019年5月30日
faith帅军  LV7 2019年5月12日
1812215714  LV8 2019年4月29日
itlaolang  LV5 2019年1月18日
adminmwx  LV20 2018年12月27日
夕四呀  LV6 2018年12月20日
我一直在笑  LV10 2018年10月12日
pakadp  LV4 2018年5月17日
最近浏览更多
iiiiiiixiiiiii  LV1 2023年12月31日
Weishenghui  LV7 2023年10月20日
he2yong  LV11 2022年7月18日
qujianbo  LV1 2022年4月27日
isfrand  LV4 2022年4月18日
Start1  LV15 2022年3月10日
and123456  LV11 2022年2月11日
ZiruiSong  LV7 2022年1月4日
yema2986  LV2 2021年11月18日
putifeishu108  LV7 2021年5月24日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友