package com.ehcache.test.intercepter;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
public class MethodCacheInterceptor implements MethodInterceptor,
InitializingBean {
private static final Logger logger = LoggerFactory
.getLogger(MethodCacheInterceptor.class);
private transient Cache cache;
public void setCache(Cache cache) {
this.cache = cache;
}
public MethodCacheInterceptor() {
super();
}
/**
* 拦截Service/DAO 的方法,并查找该结果是否存在,如果存在就返回cache 中的值, 否则,返回数据库查询结果,并将查询结果放入cache
*/
public Object invoke(MethodInvocation invocation) throws Throwable {
String targetName = invocation.getThis().getClass().getName();
String methodName = invocation.getMethod().getName();
Object[] arguments = invocation.getArguments();
Object result;
logger.info("Find object from cache is " + cache.getName());
String cacheKey = getCacheKey(targetName, methodName, arguments);
Element element = cache.get(cacheKey);
if (element == null) {
logger.info("Hold up method , Get method result and create cache........!");
result = invocation.proceed();
element = new Element(cacheKey, (Serializable) result);
cache.put(element);
}
return element.getValue();
}
/**
* 获得cache key 的方法,cache key 是Cache 中一个Element 的唯一标识 cache key
* 包括包名+类名+方法名,如com.co.cache.service.UserServiceImpl.getAllUser
*/
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();
}
/**
* implement InitializingBean,检查cache 是否为空
*/
public void afterPropertiesSet() throws Exception {
Assert.notNull(cache,
"Need a cache. Please use setCache(Cache) create it.");
}
}
MethodCacheAfterAdvice.java
package com.ehcache.test.intercepter;
import java.lang.reflect.Method;
import java.util.List;
import net.sf.ehcache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
public class MethodCacheAfterAdvice implements AfterReturningAdvice,
InitializingBean {
private static final Logger logger = LoggerFactory
.getLogger(MethodCacheAfterAdvice.class);
private transient Cache cache;
public void setCache(Cache cache) {
this.cache = cache;
}
public MethodCacheAfterAdvice() {
super();
}
public void afterReturning(Object arg0, Method arg1, Object[] arg2,
Object arg3) throws Throwable {
String className = arg3.getClass().getName();
List list = cache.getKeys();
for (int i = 0; i < list.size(); i++) {
String cacheKey = String.valueOf(list.get(i));
if (cacheKey.startsWith(className)) {
cache.remove(cacheKey);
logger.info("remove cache " + cacheKey);
}
}
}
public void afterPropertiesSet() throws Exception {
Assert.notNull(cache,
"Need a cache. Please use setCache(Cache) create it.");
}
}
测试
UserService
package com.ehcache.test.inf;
public interface UserService {
public void printUser(String userName);
public String getUser(String userId);
public String findUser(String userId);
public void updateUser(String user);
public void delUser(String userId);
}
接口实现类UserServiceImp
package com.ehcache.test.inf.impl;
import com.ehcache.test.inf.UserService;
public class UserServiceImp implements UserService {
@Override
public void printUser(String userName) {
// TODO Auto-generated method stub
System.out.println("printUser user:" + userName);// 显示user
}
@Override
public String findUser(String userId) {
// TODO Auto-generated method stub
return userId + "-- result";
}
@Override
public void updateUser(String user) {
// TODO Auto-generated method stub
System.out.println("updateUser:" + user);
}
@Override
public void delUser(String userId) {
// TODO Auto-generated method stub
System.out.println("delete user:" + userId);
}
@Override
public String getUser(String userId) {
// TODO Auto-generated method stub
return userId + "--result";
}
}
测试类
package com.ehcache.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.ehcache.test.inf.UserService;
public class TestEhcache {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"classpath:spring_beans.xml");
UserService us = (UserService) ctx.getBean("userService");
System.out.println("1--第一次查找并创建cache");
us.getUser("zhangsan");
System.out.println("2--在cache中查找");
us.getUser("zhangsan");
System.out.println("3--remove cache");
us.updateUser("zhangsan");
System.out.println("4--需要重新查找并创建cache");
us.getUser("zhangsan");
}
}