mybatis配置ehcache缓存

1:在spring配置文件中加载缓存配置文件 
  <!-- 使用ehcache缓存 -->    
   <bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">  
     <property name="configLocation" value="classpath:ehcache.xml" />  
   </bean>
  
2:ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>  
<ehcache>
  <!-- 
    maxElementsInMemory:缓存中最大允许创建的对象数
    maxInMemory:设定内存中创建对象的最大值。
    eternal:设置元素(译注:内存中对象)是否永久驻留。如果是,将忽略超时限制且元素永不消亡。
    timeToIdleSeconds:设置某个元素消亡前的停顿时间。
    timeToLiveSeconds:为元素设置消亡前的生存时间. 
    overflowToDisk:设置当内存中缓存达到 maxInMemory 限制时元素是否可写到磁盘上。
    memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
    diskPersistent:重启时内存不持久化到硬盘。
   -->
   
    <diskStore path="java.io.tmpdir"/>
    <defaultCache maxElementsInMemory="10000" memoryStoreEvictionPolicy="LRU" eternal="false"
    timeToIdleSeconds="300" timeToLiveSeconds="300" overflowToDisk="false" diskPersistent="false" />
        
    <cache name="districtDataCache"
       maxElementsInMemory="4000"
       eternal="true"
       overflowToDisk="false"
       diskPersistent="false"
       memoryStoreEvictionPolicy="LRU"/>    
</ehcache>

上面的diskStor path 你可以指定某一个路径下,java.io.tmpdir 指的是你系统的缓存目录。

3:mapper.xml
然后在对应的mapper.xml里面加上
 
<cache readOnly="true">
  <property name="timeToIdleSeconds" value="3600"/><!--1 hour-->  
    <property name="timeToLiveSeconds" value="3600"/><!--1 hour-->  
    <property name="maxEntriesLocalHeap" value="1000"/>  
    <property name="maxEntriesLocalDisk" value="10000000"/>  
    <property name="memoryStoreEvictionPolicy" value="LRU"/>  
  </cache>
(1)property参数配置不加也可以,都会有一个默认值,大家也可以查查一共有哪些配置,然后根据自己的需要来配置,然后这个配置是会带上cache执行的日志,如果不要带日志可以把LogginEhcache改成EhcacheCache。
(2)如果readOnly为false,此时要结果集对象必须是可序列化的。需要将实体对象implements Serializable

4:useCache开关
在mapper.xml这样设置了默认是全部操作都会执行缓存策略,如果有某些sql不需要执行,可以把useCache设置为false。

<select id="selectUser" resultMap="BaseResultMap" parameterType="XX.XX.XX.XX.User" useCache="false" >

小结:
其实mybatis缓存不是最好的选择:
a、面对一定规模的数据量,内置的cache方式就派不上用场了;
b、对查询结果集做缓存并不是MyBatis框架擅长的,它专心做的应该是sql mapper。采用此框架的Application去构建缓存更合理,比如采用OSCache、Memcached啥的。

  

原文地址:https://www.cnblogs.com/ipetergo/p/6807470.html