配置
(1)在maven的pom.xml文件中添加如下依赖:
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.7.5</version>
</dependency>
(2)在spring-mybatis中添加如下配置:
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache.xml"></property>
</bean>
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="ehcache"></property>
</bean>
<cache:annotation-driven cache-manager="cacheManager" />
(3)编写ehcache.xml文件
<defaultCache maxElementsInMemory="10000" eternal="false"
overflowToDisk="true" timeToIdleSeconds="10" timeToLiveSeconds="20"
diskPersistent="false" diskExpiryThreadIntervalSeconds="120" />
<cache name="studentCache" maxElementsInMemory="1000" eternal="false"
overflowToDisk="true" timeToIdleSeconds="10" timeToLiveSeconds="20" />
(4)在自己的mapper文件中添加
<cache type="org.mybatis.caches.ehcache.LoggingEhcache" />
(5)在编写的要使用缓存的sevice层中使用
@Cacheable(value = { "studentCache" })
注意
这里的二级缓存的范围是以maper文件的包名来定义它的作用范围的,也就是在同一个包名下的mapper文件公用一个二级缓存