ehcache + spring+mybatis整合

    xiaoxiao2025-12-11  3

    一、 Mybatis+Ehcache配置

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

        整合MyBatis和ehcache需要的jar包如下:

    ehcache-core-2.4.4.jar

    mybatis-ehcache-1.0.0.jar

    slf4j-api-1.6.1.jar

    slf4j-log4j12-1.6.2.jar

    资源已上传到百度网盘点击此处下载,其中包括了一些mybatis的jar包,log4j,mysql驱动等必须的包

    将上述包加入项目之后,新建一个文件名,该文件名必须为ehcache.xml,放在类路径下面,内容如下:

    ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 <? xml  version = "1.0"  encoding = "UTF-8" ?> < ehcache  xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"  xsi:noNamespaceSchemaLocation = "../bin/ehcache.xsd" >          < diskStore  path = "java.io.tmpdir" />           <!-- 缓存位置可以是自定义的硬盘地址也可以是JVM默认使用的缓存地址-->          <!--<diskStore path="d:\cache"/> -->          < defaultCache  maxElementsInMemory = "10000"  eternal = "false"  timeToIdleSeconds = "30"  timeToLiveSeconds = "30"  overflowToDisk = "true" />             <!--               配置自定义缓存              name:Cache的唯一标识              maxElementsInMemory:缓存中允许创建的最大对象数              maxElementsOnDisk:磁盘中最大缓存对象数,若是0表示无穷大              eternal:Element是否永久有效,一但设置了,timeout将不起作用,对象永不过期。             timeToIdleSeconds:缓存数据的钝化时间,也就是在一个元素消亡之前,                                  两次访问时间的最大时间间隔值,这只能在元素不是永久驻留时有效,                                  如果该值是 0 就意味着元素可以停顿无穷长的时间。              timeToLiveSeconds:缓存数据的生存时间,也就是一个元素从构建到消亡的最大时间间隔值,                               这只能在元素不是永久驻留时有效,如果该值是0就意味着元素可以停顿无穷长的时间。              overflowToDisk:内存不足时,是否启用磁盘缓存。              diskPersistent:是否缓存虚拟机重启期数据      diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒         diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区              memoryStoreEvictionPolicy:缓存满了之后的淘汰算法。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)              <cache name="SimplePageCachingFilter"                   maxElementsInMemory="10000"                   eternal="false"                  overflowToDisk="false"                   timeToIdleSeconds="900"                   timeToLiveSeconds="1800"                  memoryStoreEvictionPolicy="LFU" />    --> </ ehcache >

    该文件是ehcache的配置文件,上面的注释已经说得很清楚了,这里我用的是默认的配置

    至此ehcache已经配置好了,然后只需要在你想要缓存的mapper配置文件里面加入以下内容,该查询语句得到的结果将会被缓存

    ? 1 2 3 4 5 6 7 8 9 <? 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.qiuqiu.dao.PersonDao" >      <!-- 以下两个<cache>标签二选一,第一个可以输出日志,第二个不输出日志 只要在对应的mapper配置文件中加入<cache />标签即可-->        < cache  type = "org.mybatis.caches.ehcache.LoggingEhcache" />         <!-- <cache type="org.mybatis.caches.ehcache.EhcacheCache"/> -->      < select  id = "selectUserById"  parameterType = "int"  resultType = "org.qiuqiu.vo.Person" >              select * from person where id=#{id}       </ select > </ mapper >

    这样就对这个mapper里面的各种结果进行了缓存。程序中不需要修改任何地方。

    这个过程不复杂,也没什么难度,不过Mybatis的官方说的也太含糊了。附件下面有,需要的各种jar包已经包含。

    ecache+mybatis pom

    <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>2.10.1</version> </dependency> <dependency> <groupId>org.mybatis.caches</groupId> <artifactId>mybatis-ehcache</artifactId> <version>1.0.3</version> </dependency>

    二、 springMVC+mybatis+ehcache详细配置

        首先需要先需要两个主要的jar包

    ehcache-core-2.4.6.jar

    mybatis-ehcache-1.0.1.jar

        ehcache-core一定要1.3以上的版本 因为1.3之前好像不支持集群的。然后需要创建一个ehcache.xml在类路径下面

    ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 <? xml  version = "1.0"  encoding = "utf-8" ?>         < ehcache  xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"  xsi:noNamespaceSchemaLocation = "ehcache.xsd" >                   < diskStore  path = "java.io.tmpdir" />        < defaultCache  maxElementsInMemory = "10000"  eternal = "false"  timeToIdleSeconds = "30"  timeToLiveSeconds = "30"  overflowToDisk = "false" />        <!--                 配置自定义缓存                maxElementsInMemory:缓存中允许创建的最大对象数                eternal:缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期。                timeToIdleSeconds:缓存数据的钝化时间,也就是在一个元素消亡之前,                                            两次访问时间的最大时间间隔值,这只能在元素不是永久驻留时有效,                                            如果该值是 0 就意味着元素可以停顿无穷长的时间。                timeToLiveSeconds:缓存数据的生存时间,也就是一个元素从构建到消亡的最大时间间隔值,                                      这只能在元素不是永久驻留时有效,如果该值是0就意味着元素可以停顿无穷长的时间。                overflowToDisk:内存不足时,是否启用磁盘缓存。                memoryStoreEvictionPolicy:缓存满了之后的淘汰算法。            -->             < cache  name = "testCache"                 maxElementsInMemory = "10000"                 eternal = "true"                overflowToDisk = "false"                 timeToIdleSeconds = "0"                 timeToLiveSeconds = "600"                memoryStoreEvictionPolicy = "LFU"  />   </ ehcache >

        上面的diskStor path 你可以指定某一个路径下,java.io.tmpdir 指的是你系统的缓存目录,可以百度下然后一般这个xml都需要有一个defaultCache,就是默认的cache配置  里面有哪些参数自己可以网上查查api

        然后下面我还配置了一个testCache,我找网上资料 没看到哪里明说,然后我自己测试,发现ehcache是可以生成多个cache的,每个cache可以根据不同的业务场景作用于不同的业务(即里面的参数配置不同),所以这样看似多配置了,其实是更加增加了灵活性。

    然后在spring的配置文件里面加上一段配置:

    ? 1 2 3 4 <!-- 使用ehcache缓存 -->         < bean  id = "ehCacheManager"  class = "org.springframework.cache.ehcache.EhCacheManagerFactoryBean" >         < property  name = "configLocation"  value = "classpath:ehcache.xml"  />       </ bean >

    这样就可以把ehcache和spring整合起来了

    然后在对应的mapper.xml 里面加上

    ? 1 2 3 4 5 6 7 < cache  type = "org.mybatis.caches.ehcache.LoggingEhcache"  >        < 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 >

        后面的参数配置不加也可以,都会有一个默认值,大家也可以查查一共有哪些配置,然后根据自己的需要来配置,然后这个配置是会带上cache执行的日志,如果不要带日志可以把LogginEhcache改成EhcacheCache。

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

    ? 1 < select  id = "selectByExample"  resultMap = "BaseResultMap"  parameterType = "com.anenjoy.manage.entity.TblUserTempExample"  useCache = "false"  >

        其实经过这样的配置ehcache已经基本OK了。接下来就测试一下。

    原文测试代码如下:

    ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 long  begin = System.nanoTime();            tempService.selectAll();            long  end = System.nanoTime() - begin;            System.out.println( "count :"  + end);            // the second time            begin = System.nanoTime();            try  {                tempService.insertTblUserTemp( "1" ,  "1" ,  "1" ,  "1" );            }  catch  (NoSuchAlgorithmException e) {                e.printStackTrace();            }            end = System.nanoTime() - begin;            System.out.println( "count :"  + end);            // the second time            begin = System.nanoTime();            tempService.selectAll();            end = System.nanoTime() - begin;            System.out.println( "count :"  + end);            // the third time            begin = System.nanoTime();            tempService.selectAll();            end = System.nanoTime() - begin;            System.out.println( "count :"  + end);            return  "" ;

    这里面有4条输出语句

    首先是查询一次某表     执行了查询sql

    然后给某表插入一条信息  执行了插入sql

    然后再查询某表   执行了查询sql,这是正确的  因为你执行了非查询语句,这个时候需要重新访问数据库

    然后再一次查询某表  没有执行查询sql    这代表缓存是有用的,他就没有访问数据库了,直接从内存或者磁盘里面获取了

    也可以根据count来查看操作的时间

    count :681719

    ————————————————-com.anenjoy.manage.mapper.TblUserTempMapper.insert

    insert into TBLUSERTEMP (ACTIVECODE, PASSWORDMD5, PASSWORDRANDOMKEY,

    PHONE, EMAIL, USERNAME,

    AWARTAR, STATUS, CREATEDATE,

    USERID, IMSI, CHECKCODE

    )

    values (?, ?, ?,

    ?, ?, ?,

    ?, ?, ?,

    ?, ?, ?

    )

    count :129557388

    ————————————————-com.anenjoy.manage.mapper.TblUserTempMapper.selectByExample

    select

    ACTIVECODE, PASSWORDMD5, PASSWORDRANDOMKEY, PHONE, EMAIL, USERNAME, AWARTAR, STATUS,

    CREATEDATE, USERID, IMSI, CHECKCODE

    from TBLUSERTEMP

    count :333938203

    count :560704

    然后这些基本上OK了

    最新回复(0)