ehcache 的基本配置和使用

来源:互联网 发布:网络3d游戏大全 编辑:程序博客网 时间:2024/06/06 00:20

首先需要在spring 的applicationContext.xml 中对要使用的具体缓存技术进行配置:

<!-- 使用ehcache缓存 -->
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:config/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" />


/ehcache.xml 配置如下:

<?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"/>
    <!--
    配置自定义缓存
    maxElementsInMemory:缓存中允许创建的最大对象数
    eternal:缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期。
    timeToIdleSeconds:缓存数据的钝化时间,也就是在一个元素消亡之前,
                    两次访问时间的最大时间间隔值,这只能在元素不是永久驻留时有效,
                    如果该值是 0 就意味着元素可以停顿无穷长的时间。
    timeToLiveSeconds:缓存数据的生存时间,也就是一个元素从构建到消亡的最大时间间隔值,
    这只能在元素不是永久驻留时有效,如果该值是0就意味着元素可以停顿无穷长的时间。
    overflowToDisk:内存不足时,是否启用磁盘缓存。
    memoryStoreEvictionPolicy:缓存满了之后的淘汰算法。

以上为常用属性设置和说明,其他更多属性不再进行说明,其name值将与使用缓存时候的@Cacheable的value值相同
    -->
    <!--静态数据缓存-->
    <cache name="commonCache"
           maxElementsInMemory="10000"
           eternal="false"
           overflowToDisk="false"
           timeToIdleSeconds="0"
           timeToLiveSeconds="600"
           memoryStoreEvictionPolicy="LFU" />

    <!-- 用户相关   -->
    <cache name="userCommentCountCache"
           maxElementsInMemory="10000"
           eternal="false"
           overflowToDisk="false"
           timeToIdleSeconds="0"

           timeToLiveSeconds="3600"
           memoryStoreEvictionPolicy="LFU" />
</ehcache>


缓存直接使用spring的缓存注解@Cacheable,该注解可以用于类或者方法,用于类则所有方法都将被缓存。

该注解有三个属性值,value 指明缓存的位置与配置文件中的那么值相同,key和condition则使用spring的el表达式,

key说明被缓存的key-value缓存的key值,默认值为方法名;condition为存储或查找缓存的条件值,如 "#mac!=null"  -->  mac字段不等于null    "#age>20" 年龄大于20

@Cacheable(value = "commonCache", key = "#root.methodName+'_'+#mac",condition = "#mac!=null")
    public Boolean isBlackMacList(String mac) {
    CommentBlackListExample example =  new CommentBlackListExample();
    example.createCriteria().andMacEqualTo(mac);
    List<CommentBlackList> list = commentBlackListMapper.selectByExample(example);
        return list != null && !list.isEmpty();
    }