spring ehcache 的配置

本文详细介绍了如何在Spring框架中利用EHCache实现方法级别的缓存,包括引入依赖、配置缓存管理器、创建缓存、定义拦截器及实现缓存拦截器的代码解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.引入ehcache-1.2.4.jar
2.引入ehcache.xml
在dataAccessContext-local.xml中填写
<!-- ======================   DEFINITIONS OF CACHE METHOD   ======================= -->
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation">
<value>/WEB-INF/ehcache.xml</value> //引用ehcache.xml路径
</property>
</bean>

<bean id="methodCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean">
<property name="cacheManager">
<ref local="cacheManager"/>
</property>
<property name="cacheName">
<value>WAPCACHE</value> //设置所使用的cache name
</property>
</bean>

methodCache 这个Bean 创建了 WAPCACHE这个cache

3.配置ehcache.xml文件
<ehcache>
<!—设置缓存文件 .data 的创建路径。
如果该路径是 Java 系统参数,当前虚拟机会重新赋值。
下面的参数这样解释:
user.home – 用户主目录
user.dir – 用户当前工作目录
java.io.tmpdir – 默认临时文件路径,就是在tomcat的temp目录 -->
<diskStore path="java.io.tmpdir"/>
<!—缺省缓存配置。CacheManager 会把这些配置应用到程序中。
下列属性是 defaultCache 必须的:
maxInMemory - 设定内存中创建对象的最大值。
eternal - 设置元素(译注:内存中对象)是否永久驻留。如果是,将忽略超
时限制且元素永不消亡。
timeToIdleSeconds - 设置某个元素消亡前的停顿时间。
也就是在一个元素消亡之前,两次访问时间的最大时间间隔值。
这只能在元素不是永久驻留时有效(译注:如果对象永恒不灭,则
设置该属性也无用)。
如果该值是 0 就意味着元素可以停顿无穷长的时间。
timeToLiveSeconds - 为元素设置消亡前的生存时间。
也就是一个元素从构建到消亡的最大时间间隔值。
这只能在元素不是永久驻留时有效。
overflowToDisk - 设置当内存中缓存达到 maxInMemory 限制时元素是否可写到磁盘
上。
-->
<!--timeToLiveSeconds的时间一定要大于等于timeToIdleSeconds的时间按-->

<defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" />
<cache name="WAPCACHE" //cache name
maxElementsInMemory="10000" //内存中存储的对象的个数
eternal="false" //cache中的对象是否过期,缺省为过期(按照配置中的时间),如果改为true,表示该对象永远不过期

timeToIdleSeconds="1800" //对象限制多少秒过期
timeToLiveSeconds="3600" //对象存活多少秒过期
overflowToDisk="true" //对象在内存中达到最大个数的时候,是否写入硬盘
/>
</ehcache>


4.定义MethodCacheInterceptor拦截器
在dataAccessContext-local.xml中填写
<!-- ========================= Cache WAP FACADE ========================================== -->
<bean id="methodCacheInterceptor" class="com.lenovomobile.wap.cache.MethodCacheInterceptor">
<property name="wapCache">
<ref local="methodCache" />
</property>
</bean>

//注:methodCacheInterceptor拦截器实现了org.aopalliance.intercept.MethodInterceptor接口。
//一旦运行起来,它首先检查被拦截方法是否被配置为可缓存的。这将可选择性的配置想要缓存的 bean 方法,只要调用的方法配置为可缓存,拦截器将为该方法生成 cache key 并检查该方法返回的结果是否已缓存。
//如果已缓存,就返回缓存的结果,否则再次调用被拦截方法,并缓存结果供下次调用。

//如果想对bean中的一部分方法进行缓存,如对一些Bean的所有get方法进行缓存,需要在你的spring配置文件中加入如下代码:

<bean id="methodCachePointCut" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<property name="advice">
<ref local="methodCacheInterceptor"/>
</property>
<property name="pattern">
<value>.*get.*</value> 对get方法进行cache
</property>
</bean>

//methodCachePointCut用于拦截get方法名的方法,可以根据需要任意增加所需要拦截方法的名称。

<bean id="pageDao" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>com.lenovomobile.wap.dao.PageDao</value>
</property>

<property name="target" ref="realPageDao"/>
<property name="interceptorNames">
<list>
<value>methodCachePointCut</value>
</list>
</property>
</bean>

<bean id="columnDao" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>com.lenovomobile.wap.dao.ColumnDao</value>
</property>

<property name="target" ref="realColumnDao"/>
<property name="interceptorNames">
<list>
<value>methodCachePointCut</value>
</list>
</property>
</bean>

<bean id="topAdsDao" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>com.lenovomobile.wap.dao.TopAdsDao</value>
</property>

<property name="target" ref="realTopAdsDao"/>
<property name="interceptorNames">
<list>
<value>methodCachePointCut</value>
</list>
</property>
</bean>


<bean id="bookmarkDao" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>com.lenovomobile.wap.dao.BookmarkDao</value>
</property>

<property name="target" ref="realBookmarkDao"/>
<property name="interceptorNames">
<list>
<value>methodCachePointCut</value>
</list>
</property>
</bean>

注:如果你要缓存的方法是 getXXX,那么正则表达式应该这样写:“.*get.*”。

5. 实现MethodCacheInterceptor.java,具体如下
	package com.lenovomobile.wap.cache;

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

/**
* @author Administrator
*
* TODO 缓存处理
*/
public class MethodCacheInterceptor implements MethodInterceptor,
InitializingBean {

private Logger logger = Logger.getLogger("Method-Cache-Inegceptor");

private Cache wapCache;

/**
* 设置缓存名
*/
public void setWapCache(Cache wapCache) {
this.wapCache = wapCache;
}

/**
* 主方法
* 如果某方法可被缓存就缓存其结果
* 方法结果必须是可序列化的(serializable)
*/
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("looking for method result in cache");
String cacheKey = getCacheKey(targetName, methodName, arguments);
logger.info("cache key" + cacheKey);
Element element = wapCache.get(cacheKey);
if (element == null) {
// call target/sub-interceptor
logger.info("calling intercepted method");
result = invocation.proceed();

// cache method result
logger.info("caching result");
element = new Element(cacheKey, (Serializable) result);
wapCache.put(element);
}
return element.getValue();
}

/**
* 检查是否提供必要参数。
*/
public void afterPropertiesSet() throws Exception {
Assert.notNull(wapCache,
"A cache is required. Use setCache(Cache) to provide one.");
}

/**
* creates cache key: targetName.methodName.argument0.argument1...
*/
private String getCacheKey(String targetName, String methodName,
Object[] arguments) throws Exception {
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();
}

}


MethodCacheInterceptor 代码说明了:

默认条件下,所有方法返回结果都被缓存了( methodNames 是 null )

缓存区利用 IoC 形成

cacheKey 的生成还包括方法参数的因素(译注:参数的改变会影响 cacheKey

参考:http://opensource.atlassian.com/confluence/spring/display/DISC/Caching+the+result+of+methods+using+Spring+and+EHCache
内容概要:本文探讨了在MATLAB/SimuLink环境中进行三相STATCOM(静态同步补偿器)无功补偿的技术方法及其仿真过程。首先介绍了STATCOM作为无功功率补偿装置的工作原理,即通过调节交流电压的幅值和相位来实现对无功功率的有效管理。接着详细描述了在MATLAB/SimuLink平台下构建三相STATCOM仿真模型的具体步骤,包括创建新模型、添加电源和负载、搭建主电路、加入控制模块以及完成整个电路的连接。然后阐述了如何通过对STATCOM输出电压和电流的精确调控达到无功补偿的目的,并展示了具体的仿真结果分析方法,如读取仿真数据、提取关键参数、绘制无功功率变化曲线等。最后指出,这种技术可以显著提升电力系统的稳定性与电能质量,展望了STATCOM在未来的发展潜力。 适合人群:电气工程专业学生、从事电力系统相关工作的技术人员、希望深入了解无功补偿技术的研究人员。 使用场景及目标:适用于想要掌握MATLAB/SimuLink软件操作技能的人群,特别是那些专注于电力电子领域的从业者;旨在帮助他们学会建立复杂的电力系统仿真模型,以便更好地理解STATCOM的工作机制,进而优化实际项目中的无功补偿方案。 其他说明:文中提供的实例代码可以帮助读者直观地了解如何从零开始构建一个完整的三相STATCOM仿真环境,并通过图形化的方式展示无功补偿的效果,便于进一步的学习与研究。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值