spring+Mybatis+Ehcache整合

 

项目用到spring+mybatis框架,弄了一上午的spring+ehcache的整合,就是不见效果,后来发现Mybatis与Ehcache整合也需要进行配置,两个都配置会大大降低数据库压力。下面把我的配置过程写下来供大家参考。

 

1. 下载mybatis相关包与ehcache相关包

下载地址为:https://github.com/mybatis/ehcache-cache/releases

2. 在Map文件中打开echached效果,userMapper.xml文件内容如下:

 

Java代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >  
  3. <mapper namespace="com.erpbase.dao.UserMapper">  
  4.               <!-- 以下两个<cache>标签二选一,第一个可以输出日志,第二个不输出日志 -->  
  5.     <cache type="org.mybatis.caches.ehcache.LoggingEhcache" />  
  6.     <cache type="org.mybatis.caches.ehcache.EhcacheCache" />  
  7.     ......  
  8. </mapper>  

 3. 配置ehcache.xml 

 

Java代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>    
  2. <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">  
  3.     <diskStore path="java.io.tmpdir"/>   
  4.      
  5.     <defaultCache      
  6.             maxElementsInMemory="3000"      
  7.             eternal="false"      
  8.             timeToIdleSeconds="3600"      
  9.             timeToLiveSeconds="3600"      
  10.             overflowToDisk="true"      
  11.             diskPersistent="false"      
  12.             diskExpiryThreadIntervalSeconds="100"      
  13.             memoryStoreEvictionPolicy="LRU"      
  14.             />      
  15.     <cache name="userCache"      
  16.            maxElementsInMemory="3000"      
  17.            eternal="false"      
  18.            overflowToDisk="true"      
  19.            timeToIdleSeconds="3600"      
  20.            timeToLiveSeconds="3600"      
  21.            memoryStoreEvictionPolicy="LFU"      
  22.             />    
  23.     ......  
  24. </ehcache>  

 参数说明:

 

 <!-- 

        name: cache的名字,用来识别不同的cache,必须惟一。   

maxElementsInMemory: 内存管理的缓存元素数量最大限值。   

maxElementsOnDisk: 硬盘管理的缓存元素数量最大限值。默认值为0,就是没有限制。   

eternal: 设定元素是否持久话。若设为true,则缓存元素不会过期。   

overflowToDisk: 设定是否在内存填满的时候把数据转到磁盘上。

timeToIdleSeconds: 设定元素在过期前空闲状态的时间,只对非持久性缓存对象有效。默认值为0,值为0意味着元素可以闲置至无限长时间。   

timeToLiveSeconds: 设定元素从创建到过期的时间。其他与timeToIdleSeconds类似。   

diskPersistent: 设定在虚拟机重启时是否进行磁盘存储,默认为false.(我的直觉,对于安全小型应用,宜设为true)。   

diskExpiryThreadIntervalSeconds: 访问磁盘线程活动时间。   

diskSpoolBufferSizeMB: 存入磁盘时的缓冲区大小,默认30MB,每个缓存都有自己的缓冲区。   

memoryStoreEvictionPolicy: 元素逐出缓存规则。共有三种,Recently Used (LRU)最近最少使用,为默认。 First In First Out (FIFO),先进先出。Less Frequently Used(specified as LFU)最少使用  

--> 

4. 配置applicationContext-ehcache.xml

 

Java代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!-- /** * * 缓存配置 *  * */ -->  
  3. <beans xmlns="http://www.springframework.org/schema/beans"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xmlns:ehcache="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring"  
  6.     xsi:schemaLocation="      
  7.     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd      
  8.     http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring    
  9.     http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.1.xsd">  
  10.   
  11.     <!-- <ehcache:annotation-driven /> -->  
  12.   
  13.     <ehcache:annotation-driven cache-manager="ehcacheManager" />  
  14.   
  15.     <ehcache:config cache-manager="ehcacheManager">  
  16.         <ehcache:evict-expired-elements interval="60" />  
  17.     </ehcache:config>  
  18.       
  19.     <bean id="ehcacheManager"  
  20.         class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">  
  21.         <property name="configLocation" value="classpath:ehcache.xml" />  
  22.     </bean>  
  23. </beans>  

 5. 在spring-mvc.xml 中加入如下内容,将ehcache相关配置装配到spring容器中:

 

 

Java代码   收藏代码
  1. <!-- 加载ehcache缓存配置文件     
  2.         说明:在这里我遇到了这样一个问题,当使用@Service等注解的方式将类声明到配置文件中时,    
  3.         就需要将缓存配置import到主配置文件中,否则缓存会不起作用    
  4.         如果是通过<bean>声明到配置文件中时,    
  5.         则只需要在web.xml的contextConfigLocation中加入applicationContext-ehcache.xml即可,    
  6.         不过还是推荐使用如下方式吧,因为这样不会有任何问题    
  7.     -->    
  8.     <import resource="classpath:applicationContext-ehcache.xml"/>  

 6. 在userServiceImpl.java中加入通过注解进行配置:

 

 

Java代码   收藏代码
  1.        @Cacheable(cacheName="userCache")  <strong>//这里的cacheName要跟ehcache.xml中保持一致</strong>  
  2. public List<User> getUserList(User user, Map<String, Object> map) {  
  3.     long l1 = new Date().getTime();  
  4.   
  5.     List<User> list = userMapper.getUserList(user);  
  6.     Integer listSize = userMapper.getUserCount(user);  
  7.   
  8.     long l2 = new Date().getTime();  
  9.     System.out.println("++++++++++++total time use: " + (l2-l1));  
  10.   
  11.     map.put("rows", list);  
  12.     map.put("total", listSize);  
  13.   
  14.     return list;  
  15. }  

 

 

到此spring+mybatis+EHCache配置完成。可以对比在加上@Cacheable(cacheName="userCache")和不加的两种情况下的(l2-l1)的时间,在我本地如果不加用时在40ms左右,加上之后第一次加载是40ms,第二次用时1ms,说明第一次加载的数据已经被放到缓存当中去,可见效率得到极大提升。

 

 

 

拓展说明:

对于清除缓存的方法,ehcache提供了两种,一种是在ehcache.xml中配置的时间过后自动清除,一种是在数据发生变化后触发清除。个人感觉第二种比较好。可以将 

@TriggersRemove(cacheName="userCache",removeAll=true)

@TriggersRemove(cacheName="userCache", when=When.AFTER_METHOD_INVOCATION, removeAll=true) 

这句代码加到service里面的添加、删除、修改方法上。这样只要这几个方法有调用,缓存自动清除。

 

对于Mybatis更简单,对不想缓存的sql结果,可以再后面添加useCache="false"即可:

Java代码   收藏代码
  1. <select id="getLabelValueList" resultMap="BaseResultMap" parameterType="com.Product" useCache="false">  
  2. select Id, Name  
  3. from Product  
  4. where Enable = 1  
  5. <if test="shopid != null and shopid != 0 " >  
  6.   AND Id not in (select Productid from shopproduct where shopid = #{shopid})   
  7. </if>  
  8. order by Id  
  9. </select>  
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值