SSM 配置ehcache

来源:互联网 发布:淘宝差评多少天可以改 编辑:程序博客网 时间:2024/06/14 10:59

1.添加依赖

<dependency>   <groupId>net.sf.ehcache</groupId>    <artifactId>ehcache</artifactId>    <version>2.10.4</version></dependency><dependency>    <groupId>org.mybatis</groupId>    <artifactId>mybatis-ehcache</artifactId>    <version>1.0.0</version></dependency>

2.ehcache.xml配置文件

<?xml version="1.0" encoding="UTF-8"?><ehcache name="es">    <diskStore path="java.io.tmpdir"/>    <!--<diskStore path="${java.io.tmpdir}/${system.project_name}/cache"/>-->    <!--       name:缓存名称。       maxElementsInMemory:缓存最大个数。       eternal:对象是否永久有效,一但设置了,timeout将不起作用。       timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。       timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。       overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。       diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。       maxElementsOnDisk:硬盘最大缓存个数。       diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.       diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。       memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。       clearOnFlush:内存数量最大时是否清除。    -->    <defaultCache            maxEntriesLocalHeap="1000"            eternal="false"            timeToIdleSeconds="3600"            timeToLiveSeconds="3600"            overflowToDisk="false">    </defaultCache>    <cache name="shiro-authenticationCache"           maxEntriesLocalHeap="1000"           eternal="false"           timeToIdleSeconds="600"           timeToLiveSeconds="600"           overflowToDisk="false"           statistics="true">    </cache>    <cache name="shiro-authorizationCache"           maxEntriesLocalHeap="2000"           eternal="false"           timeToIdleSeconds="600"           timeToLiveSeconds="600"           overflowToDisk="false"           statistics="true">    </cache>    <cache name="shiro-userCache"           maxEntriesLocalHeap="2000"           eternal="false"           timeToIdleSeconds="600"           timeToLiveSeconds="600"           overflowToDisk="false"           statistics="true">    </cache>    <cache name="basecache"           maxElementsInMemory="200"           maxElementsOnDisk="1000"           eternal="false"           overflowToDisk="true"           timeToIdleSeconds="300"           timeToLiveSeconds="600"           memoryStoreEvictionPolicy="LFU"           diskSpoolBufferSizeMB="20">    </cache></ehcache>

3.spring配置文件

    <!-- MyBatis使用ehcache缓存 start -->    <bean id="ehCacheManager"          class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">        <property name="configLocation" value="classpath:ehcache.xml"/>        <property name="shared" value="true"/> <!-- 这里是关键!!!没有必错  -->    </bean>    <!-- 配置 Spring 的 EhCacheCacheManager,须要 spring-context-support 的支持 -->    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">        <property name="cacheManager" ref="ehCacheManager"/>    </bean>    <!-- end MyBatis使用ehcache缓存 -->    <cache:annotation-driven cache-manager="cacheManager" />

注意 如果项目中添加了shiro 那么一定要加上<property name="shared" value="true"/> 不然会报错

使用ehcache

1.mapper.xml文件中添加<cache>

<?xml version="1.0" encoding="UTF-8" ?>   <!DOCTYPE mapper       PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"       "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.kou.mapper.HelloMapper">    <cache type="org.mybatis.caches.ehcache.LoggingEhcache" >        <property name="timeToIdleSeconds" value="3600"/>      <property name="timeToLiveSeconds" value="3600"/>      <property name="maxEntriesLocalHeap" value="1000"/>        <property name="maxEntriesLocalDisk" value="10000000"/>        <property name="memoryStoreEvictionPolicy" value="LRU"/>    </cache>    <select id="getAll" resultType="map">        select * from customer order by id desc    </select>    <delete id="deleteById" parameterType="int">        delete from customer where id = #{id}    </delete></mapper> 

LoggingEhcache 这个会在打印log,如果不像要log的话可以使用EhcacheCache

按照上面配置,这个mapper.xml里面的操作是全局,默认为useCache=”true” 都会有作用,

假如某个业务是不要缓存的,可以在当前业务下加上useCache=”false”

<select id="selectByName" resultMap="BaseResultMap" parameterType="java.lang.String" useCache="false">

2.用@Cacheable注解标注service层的查询方法

    @TriggersRemove(cacheName="baseCache",removeAll=true)    public Entity save(Entity entity) throws CrudException {        return entity;    }    @TriggersRemove(cacheName="baseCache",removeAll=true)    public Entity update(Entity entity) throws CrudException {        return entity;    }    @TriggersRemove(cacheName="baseCache",removeAll=true)    public void del(Entity entity) throws CrudException {            }    @Cacheable(value="baseCache", key = "‘findAll‘")        public List<Entity> findAll() throws SearchException {        return list;    }
  • @Cacheable(value=”baseCache”, key = “‘findAll‘”)

    • 这个注解就是做到缓存数据,cacheName对应ehcache.xml 中配置
  • @TriggersRemove(cacheName=”baseCache”,removeAll=true)

    • 这个注解的作用就是当数据发生变化的时候清除缓存,做到数据同步

@Cacheable可以指定三个属性,value、key和condition。

  1. value

    • @Cacheable(“cache1”)、@Cacheable({“cache1”, “cache2”})//Cache是发生在cache1和cache2上的

    • value属性是必须指定的,其表示当前方法的返回值是会被缓存在哪个Cache上的,对应Cache的名称。其可以是一个Cache也可以是多个Cache,当需要指定多个Cache时其是一个数组。

  2. key

    • @Cacheable(value=”users”, key=”#user.id”)、@Cacheable(value=”users”, key=”#p0”)
    • key属性是用来指定Spring缓存方法的返回结果时对应的key的。该属性支持SpringEL表达式。当我们没有指定该属性时,Spring将使用默认策略生成key。我们这里先来看看自定义策略,自定义策略是指我们可以通过Spring的EL表达式来指定我们的key。这里的EL表达式可以使用方法参数及它们对应的属性
  3. condition

    • @Cacheable(value={“users”}, key=”#user.id”, condition=”#user.id%2==0”)
    • 有的时候我们可能并不希望缓存一个方法所有的返回结果。通过condition属性可以实现这一功能。condition属性默认为空,表示将缓存所有的调用情形。其值是通过SpringEL表达式来指定的,当为true时表示进行缓存处理;当为false时表示不进行缓存处理,即每次调用该方法时该方法都会执行一次。以上下示例表示只有当user的id为偶数时才会进行缓存。

其他

  1. @CachePut(“users”)

    检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中。

    @CachePut也可以标注在类上和方法上。使用@CachePut时我们可以指定的属性跟@Cacheable是一样的。

  2. @CacheEvict(value=”users”, allEntries=true)

    allEntries是boolean类型,表示是否需要清除缓存中的所有元素。默认为false,表示不需要。当指定了allEntries为true时,Spring Cache将忽略指定的key。有的时候我们需要Cache一下清除所有的元素,这比一个一个清除元素更有效率。

  3. @CacheEvict(value=”users”, beforeInvocation=true)

    清除操作默认是在对应方法成功执行之后触发的,即方法如果因为抛出异常而未能成功返回时也不会触发清除操作。使用beforeInvocation可以改变触发清除操作的时间,当我们指定该属性值为true时,Spring会在调用该方法之前清除缓存中的指定元素。