package com.test.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.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
public class CacheMethodInterceptor implements MethodInterceptor,
InitializingBean {
private Cache cache;
public void setCache(Cache cache) {
this.cache = cache;
}
public CacheMethodInterceptor() {
super();
}
/**
* 拦截ServiceManager的方法,并查找该结果是否存在,如果存在就返回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;
//创建一个字符串,用来做cache中的key
String cacheKey = getCacheKey(targetName, methodName, arguments);
//从cache中获取数据
Element element = cache.get(cacheKey);
if (element == null) {
//如果cache中没有数据,则查找非缓存,例如数据库,并将查找到的放入cache
result = invocation.proceed();
//生成将存入cache的key和value
element = new Element(cacheKey, (Serializable) result);
System.out.println("-----进入非缓存中查找,例如直接查找数据库,查找后放入缓存");
//将key和value存入cache
cache.put(element);
} else {
//如果cache中有数据,则查找cache
System.out.println("-----进入缓存中查找,不查找数据库,缓解了数据库的压力");
}
return element.getValue();
}
/**
* 获得cache的key的方法,cache的key是Cache中一个Element的唯一标识,
* 包括包名+类名+方法名,如:com.test.service.TestServiceImpl.getObject
*/
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是否为空 70
*/
public void afterPropertiesSet() throws Exception {
Assert.notNull(cache,
"Need a cache. Please use setCache(Cache) create it.");
}
}
package com.test.ehcache;
import java.lang.reflect.Method;
import java.util.List;
import net.sf.ehcache.Cache;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
public class CacheAfterReturningAdvice implements AfterReturningAdvice,
InitializingBean {
private Cache cache;
public void setCache(Cache cache) {
this.cache = cache;
}
public CacheAfterReturningAdvice() {
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);
System.out.println("-----清除缓存");
}
}
}
public void afterPropertiesSet() throws Exception {
Assert.notNull(cache,
"Need a cache. Please use setCache(Cache) create it.");
}
}
package com.test.service;
import java.util.List;
public interface ServiceManager {
public List getObject();
public void updateObject(Object Object);
}
package com.test.service;
import java.util.ArrayList;
import java.util.List;
public class ServiceManagerImpl implements ServiceManager {
@Override
public List getObject() {
System.out.println("-----ServiceManager:缓存Cache内不存在该element,查找数据库,并放入Cache!");
return null;
}
@Override
public void updateObject(Object Object) {
System.out.println("-----ServiceManager:更新了对象,这个类产生的cache都将被remove!");
}
}
package com.test.service;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestMain {
public static void main(String[] args) {
String cacheString = "/cache-bean.xml";
ApplicationContext context = new ClassPathXmlApplicationContext(
cacheString);
//获取代理工厂proxyFactory生成的bean,以便产生拦截效果
ServiceManager testService = (ServiceManager) context.getBean("proxyFactory");
// 第一次查找
System.out.println("=====第一次查找");
testService.getObject();
// 第二次查找
System.out.println("=====第二次查找");
testService.getObject();
// 执行update方法(应该清除缓存)
System.out.println("=====第一次更新");
testService.updateObject(null);
// 第三次查找
System.out.println("=====第三次查找");
testService.getObject();
}
}
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <!-- 引用ehCache 的配置--> <bean id="defaultCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> <property name="configLocation"> <value>ehcache.xml</value> </property> </bean> <!-- 定义ehCache的工厂,并设置所使用的Cache的name,即“com.tt” --> <bean id="ehCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean"> <property name="cacheManager"> <ref local="defaultCacheManager" /> </property> <!-- Cache的名称 --> <property name="cacheName"> <value>com.tt</value> </property> </bean> <!-- 创建缓存、查询缓存的拦截器 --> <bean id="cacheMethodInterceptor" class="com.test.ehcache.CacheMethodInterceptor"> <property name="cache"> <ref local="ehCache" /> </property> </bean> <!-- 更新缓存、删除缓存的拦截器 --> <bean id="cacheAfterReturningAdvice" class="com.test.ehcache.CacheAfterReturningAdvice"> <property name="cache"> <ref local="ehCache" /> </property> </bean> <!-- 调用接口,被拦截的对象 --> <bean id="serviceManager" class="com.test.service.ServiceManagerImpl" /> <!-- 插入拦截器,确认调用哪个拦截器,拦截器拦截的方法名特点等,此处调用拦截器com.test.ehcache.CacheMethodInterceptor --> <bean id="cachePointCut" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"> <!-- 加入切面,切面为当执行完print方法后,在执行加入的切面 --> <property name="advice"> <ref local="cacheMethodInterceptor" /> </property> <property name="patterns"> <list> <!-- ### .表示符合任何单一字元 ### +表示符合前一个字元一次或多次 ### *表示符合前一个字元零次或多次 ### Escape任何Regular expression使用到的符号 --> <!-- .*表示前面的前缀(包括包名),意思是表示getObject方法--> <value>.*get.*</value> </list> </property> </bean> <!-- 插入拦截器,确认调用哪个拦截器,拦截器拦截的方法名特点等,此处调用拦截器com.test.ehcache.CacheAfterReturningAdvice --> <bean id="cachePointCutAdvice" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"> <property name="advice"> <ref local="cacheAfterReturningAdvice" /> </property> <property name="patterns"> <list> <!-- .*表示前面的前缀(包括包名),意思是updateObject方法--> <value>.*update.*</value> </list> </property> </bean> <!-- 代理工厂 --> <bean id="proxyFactory" class="org.springframework.aop.framework.ProxyFactoryBean"> <!-- 说明调用接口bean名称 --> <property name="target"> <ref local="serviceManager" /> </property> <!-- 说明拦截器bean名称 --> <property name="interceptorNames"> <list> <value>cachePointCut</value> <value>cachePointCutAdvice</value> </list> </property> </bean> </beans>
<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"> <!-- 缓存文件位置 --> <diskStore path="D:\temp\cache" /> <defaultCache maxElementsInMemory="1000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" /> <!-- 定义缓存文件信息,其中“com.tt”为缓存文件的名字 --> <cache name="com.tt" maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="300000" timeToLiveSeconds="600000" overflowToDisk="true" /> </ehcache>
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有