一、依赖包:
ehcache-core
二、ehcache.xml配置文件:
<ehcache>
<cache name="webCache"
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="60"
overflowToDisk="false"
memoryStoreEvictionPolicy="LFU"
/>
</ehcache>三、applicationContext.xml配置文件:
<bean id="defaultCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache/ehcache-app.xml" />
</bean>
<bean id="ehCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean">
<property name="cacheManager">
<ref local="defaultCacheManager"/>
</property>
<property name="cacheName" value="webCache" />
</bean>
<bean id="methodCacheInterceptor" class="com.csair.uservice.interceptor.MethodCacheInterceptor">
<property name="cache">
<ref local="ehCache"/>
</property>
</bean>
<bean id="methodPointcutAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<property name="advice">
<ref local="methodCacheInterceptor"/>
</property>
<property name="patterns">
<list>
<value>com.csair.uservice.service.impl.NoticeServiceImpl.getNoticeDTOPage</value>
</list>
</property>
</bean>
<bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="interceptorNames">
<list>
<value>methodPointcutAdvisor</value>
</list>
</property>
<property name="beanNames">
<list>
<value>noticeService</value>
</list>
</property>
</bean>四、拦截器:
public class MethodCacheInterceptor implements MethodInterceptor,
InitializingBean {
private static Logger log = Logger.getLogger(MethodCacheInterceptor.class);
private Cache cache;
@Override
public void afterPropertiesSet() throws Exception {
log.info("afterPropertiesSet");
}
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
String targetName = invocation.getThis().getClass().getName();
String methodName = invocation.getMethod().getName();
Object result = null;
String cacheKey = getCacheKey(targetName, methodName);
Element element = null;
synchronized(this) {
element = cache.get(cacheKey);
if(element == null) {
log.info("加入到缓存: " + cache.getName());
result = invocation.proceed();
element = new Element(cacheKey, (Serializable)result);
cache.put(element);
} else {
log.info("使用缓存: " + cache.getName());
}
}
return element.getObjectValue();
}
private String getCacheKey(String targetName, String methodName) {
StringBuffer sb = new StringBuffer();
sb.append(targetName).append(".").append(methodName);
return sb.toString();
}
public void setCache(Cache cache) {
this.cache = cache;
}
}五、被缓存的对象都要序列化
本文详细介绍了ehcache缓存的核心配置、Spring框架中ehcache的整合方式及应用,包括配置ehcache.xml、applicationContext.xml,实现缓存管理、缓存策略设置以及通过拦截器实现方法级缓存,确保了系统的高效性和响应速度。
11万+

被折叠的 条评论
为什么被折叠?



