1.废话不多说首先配置spring pom.xml 添加dependency
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.9.0</version>
</dependency>
maven在打包时候会自动从网上下载对应的jar包。
2.写一个ehcache配置文件 ehcache-context.xml (名字可以随便起不过后面要引入)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd">
<!-- 开启cache注解 -->
<cache:annotation-driven />
<!-- Ehcache实现 -->
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
p:cache-manager-ref="ehcacheManager" />
<bean id="ehcacheManager"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
p:config-location="classpath:config/ehcache.xml" />
</beans>
3.添加 ehcache必备的配置文件 ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd"
updateCheck="true"
monitoring="autodetect"
dynamicConfig="true">
<cache name="resourceStatCache"
maxEntriesLocalHeap="10000"
eternal="false"
timeToIdleSeconds="1200" timeToLiveSeconds="1200"
memoryStoreEvictionPolicy="LFU"
transactionalMode="off">
<persistence strategy="none" />
</cache>
</ehcache>
4. 将 之前写的 ehcache-context.xml 引入到spring 配置文件 root-context.xml
<!-- 导入ehcache配置 -->
<import resource="ehcache-context.xml"/>
5.在需要进行缓存的函数添加注解如下格式:
@Cacheable({
"resourceStatCache"
})
public List<Integer> fetchId(SearchVO searchVO, String suffix) {
return xxMapper.fetchId(suffix, searchVO);
}
大体如上面配置。配置完就可以用了,原理不懂得可以百度 很多的。
来源:oschina
链接:https://my.oschina.net/u/1045974/blog/645063