applicationContext.xml
<!-- 使用ehcache缓存 -->
<ehcache:annotation-driven cache-manager="ehcacheManager" />
<ehcache:config cache-manager="ehcacheManager">
<ehcache:evict-expired-elements interval="60" />
</ehcache:config>
<bean id="ehcacheManager"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache.xml" />
</bean>
ehcache.xml
name必须唯一
<?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="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="3000"
eternal="false"
timeToIdleSeconds="3600"
timeToLiveSeconds="3600"
overflowToDisk="true"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="100"
memoryStoreEvictionPolicy="LRU"
/>
<cache name="categoryCache"
maxElementsInMemory="3000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="3600"
timeToLiveSeconds="3600"
memoryStoreEvictionPolicy="LFU"
/>
<cache name="addressCache"
maxElementsInMemory="3000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="3600"
timeToLiveSeconds="3600"
memoryStoreEvictionPolicy="LFU"
/>
mapper中配置
<!--可以输出日志 -->
<cache type="org.mybatis.caches.ehcache.LoggingEhcache" />
service层注解
cacheNames指定配置中的名字
@Cacheable(cacheNames = "categoryCache")
@Override
public List<Category> getAll(int categoryId) {
return categoryDao.getAll(categoryId);
}
测试
环境搭建成功后启动tomcat不报错,可以比较第一次查询跟后几次查询的时间,非常明显速度提高就配置成功了.
jar依赖
compile 'org.apache.archiva.redback.components.cache:spring-cache-ehcache:2.2'
compile 'com.googlecode.ehcache-spring-annotations:ehcache-spring-annotations:1.2.0'
compile 'org.mybatis.caches:mybatis-ehcache:1.0.3'
经常错误的地方是jar包方面,还有ehcache name不唯一