需要导入的.jar包:
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/>
<cache name="sampleCache1"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
overflowToDisk="true"
/>
<cache name="myCache"
maxElementsInMemory="1000"
eternal="true"
timeToIdleSeconds="0"
timeToLiveSeconds="0"
overflowToDisk="false"
/>
</ehcache>
在你的项目的classpath路径下面创建applicationContext-ehcache.xml配置文件主要配置cacheManager工厂类以及声明cacheManager,主要配置如下(根据自己的版本配置,我用的spring3.2版本):
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd">
<cache:annotation-driven cache-manager="ehcacheManager"/>
<!-- cacheManager工厂类,指定ehcache.xml的位置 -->
<bean id="ehcacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache.xml" />
</bean>
<!-- 声明cacheManager -->
<bean id="ehcacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="ehcacheManagerFactory" />
</bean>
</beans>
第三步:
在你项目主配置文件中指定applicationContext-ehcache.xml配置文件,当然,你也可以把applicationContext-ehcache.xml中的配置放在项目的主配置文件中,为了减少配置文件的发杂程度,我单独做了一个配置文件。这样去指定:
<!--LLJ 引入缓存配置文件 -->
<import resource="classpath:applicationContext-ehcache.xml"/>
第四步:
在你serviceImpl层把你要添加缓存的方法做过注解,
@Cacheable(value="myCache",key="0")
public HashMap<String, Object> findAll(Entity entity){
logger.info("findAll entity start...");
HashMap<String, Object> map = new HashMap<String, Object>();
return map;
}
spring通过注解缓存机制的配置已经完成,接下来启动项目,开始测试,你访问注解的方法两次,如果控制台第一次打出sql语句,而第二次没有打出,说明该缓存已经配置成功。祝你好运!