`

mybatis3添加Ehcache缓存

阅读更多

 

总结:无论是采用mybatis 自身的cache  还是三方的cache , 这样的配置,就是对 所有的select 语句都全局缓存

 

为了提高MyBatis的性能,有时候我们需要加入缓存支持,目前用的比较多的缓存莫过于ehcache缓存了,ehcache性能强大,而且位各种应用都提供了解决方案,在此我们主要是做查询缓存,提高查询的效率.

 

 Ehcache缓存:
  加入ehcache.xml、ehcache-2.10.0.jar(net.sf) 、mybatis-ehcache-1.0.3.jar

 

 Maper中加入:
 <cache type="org.mybatis.caches.ehcache.LoggingEhcache"/> 
    <!-- <cache type="org.mybatis.caches.ehcache.EhcacheCache"/> -->

 

说明: cache的名称: Cache Hit Ratio [cn.mapper.UserMapper] ,与namespace相同

 

 

  ehcache.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
 <!-- 默认的磁盘缓存目录 -->
    <diskStore path="java.io.tmpdir"/>
   
    <!-- EhCache是Hibernate的二级缓存技术之一,可以把查询出来的数据存储在内存或者磁盘,节省下次同样查询语句再次查询数据库,大幅减轻数据库压力 -->
    <!-- 默认缓存策略 -->
    <defaultCache
        maxElementsInMemory="10000"
        eternal="false"
        overflowToDisk="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120" />
   
    <!-- 用于整合Hibernate二级缓存:缓存领域对象
    <cache name="cn.domain.User"
        maxElementsInMemory="10000"
        eternal="false"
        overflowToDisk="false"
        timeToIdleSeconds="300"
        timeToLiveSeconds="600" />
    -->

 

</ehcache>

 

UserMapper.xml

 

<?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="cn.mapper.UserMapper" >

 <!-- 以下两个<cache>标签二选一,第一个可以输出日志,第二个不输出日志 --> 
<!--     <cache type="org.mybatis.caches.ehcache.LoggingEhcache" />   -->
    <cache type="org.mybatis.caches.ehcache.EhcacheCache"/> 

 

</mapper>

 

 

 <settings>
  <!-- 全局的映射器启用或禁用缓存。 -->
  <setting name="cacheEnabled" value="true" />

</settings>

 

/**使用了查询缓存,只查询了一次数据库*/
 static void testEhcache(UserService userService){
  testPage(userService);
  
  testPage(userService);
 }

 

 

 

 

/*使用cn.domain.User  cache 缓存对象*/
 static void testSpringEhcache(ApplicationContext app, UserService userService){
  CacheManager cm=(CacheManager)app.getBean("ehCacheManager");
  
  Cache cache=cm.getCache("cn.domain.User");
  User user=userService.selectById("100");
  Element e=new Element(user.getUserId(), user);
  
  cache.put(e);
  
  User u = (User)cache.get("100").getObjectValue();
  
  System.out.println(user);
 }

 

 <cache name="cn.domain.User"
        maxElementsInMemory="10000"
        eternal="false"
        overflowToDisk="false"
        timeToIdleSeconds="300"
        timeToLiveSeconds="600" />

 

<!-- Ehcache与spring整合 -->
 <bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:shared="true">
  <property name="configLocation" value="classpath:ehcache.xml" />
 </bean>

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics