SSM二级缓存ehcache

配置

    (1)在maven的pom.xml文件中添加如下依赖:
    <!-- ehcache 相关依赖 -->
        <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>  

    <!-- 开启spring缓存 可以使用注解来使用缓存 -->
    <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文件中添加
 <!--在mapper文件中的头部引入缓存策略 -->
 <cache type="org.mybatis.caches.ehcache.LoggingEhcache" />
 (5)在编写的要使用缓存的sevice层中使用
 @Cacheable(value = { "studentCache" })

注意

    这里的二级缓存的范围是以maper文件的包名来定义它的作用范围的,也就是在同一个包名下的mapper文件公用一个二级缓存

猜你喜欢

转载自blog.csdn.net/qq_24067089/article/details/77163995