Mybatis整合ehcache(maven)

1.导入依赖包

<dependency>
      <groupId>net.sf.ehcache</groupId>
      <artifactId>ehcache-core</artifactId>
      <version>2.6.8</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.25</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.25</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mybatis.caches</groupId>
      <artifactId>mybatis-ehcache</artifactId>
      <version>1.0.3</version>
    </dependency>

2.配置eache.xml文件,并放置到ClassPath下

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
    <!-- 磁盘保存路径 -->
    <diskStore path="F:/ehcache"/>

    <defaultCache
            maxElementsInMemory="1"
            maxElementsOnDisk="10000000"
            eternal="false"
            overflowToDisk="true"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
    </defaultCache>
</ehcache>

        <!--
        属性说明:
        l diskStore:当内存中不够存储时,存储到指定数据在磁盘中的存储位置。
        l defaultCache:当借助CacheManager.add("demoCache")创建Cache时,EhCache便会采用<defalutCache/>指定的的管理策略

        以下属性是必须的:
        l maxElementsInMemory - 在内存中缓存的element的最大数目
        l maxElementsOnDisk - 在磁盘上缓存的element的最大数目,若是0表示无穷大
        l eternal - 设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断
        l overflowToDisk - 设定当内存缓存溢出的时候是否将过期的element缓存到磁盘上

        以下属性是可选的:
        l timeToIdleSeconds - 当缓存在EhCache中的数据前后两次访问的时间超过timeToIdleSeconds的属性取值时,这些数据便会删除,默认值是0,也就是可闲置时间无穷大
        l timeToLiveSeconds - 缓存element的有效生命期,默认是0.,也就是element存活时间无穷大
         diskSpoolBufferSizeMB 这个参数设置DiskStore(磁盘缓存)的缓存区大小.默认是30MB.每个Cache都应该有自己的一个缓冲区.
        l diskPersistent - 在VM重启的时候是否启用磁盘保存EhCache中的数据,默认是false。
        l diskExpiryThreadIntervalSeconds - 磁盘缓存的清理线程运行间隔,默认是120秒。每个120s,相应的线程会进行一次EhCache中数据的清理工作
        l memoryStoreEvictionPolicy - 当内存缓存达到最大,有新的element加入的时候, 移除缓存中element的策略。默认是LRU(最近最少使用),可选的有LFU(最不常使用)和FIFO(先进先出)
        -->

3.在对应的mapper类中使用指定的缓存,而要使用第三方缓存则要实现Cache接口(此接口是Mybatis提供的)

<?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="mapper.UsersInfoMapper">
    <!--<cache eviction="FIFO" flushInterval="30000" readOnly="false" size="200" ></cache>-->
    <!--
    eviction:缓存的回收策略
        LRU(默认)、FIFO、SOFT、WEAK
    flushInterval:缓存刷新间隔
        缓存多长时间清空一次,默认不清空,设置一个毫秒值
        true:只读:mybatis认为所有从缓存中获取数据的操作都是只读操作,不会修改数据
                    mybatis为了加快获取速度,直接就会将数据在缓存中的引用交给用户。不安全,速度快
        false(默认):非只读:mybatis觉得获取的数据会被修改。
                        mybatis会利用序列化与反序列化技术克隆一份新的数据给你。安全,速度慢
        size:缓存存放多少元素
        type=“”,指定自定义缓存的全类名.
            实现Cache接口即可
    -->
    <cache type="org.mybatis.caches.ehcache.EhcacheCache" >
        <property name="timeToIdleSeconds" value="3600"/>
        <property name="timeToLiveSeconds" value="3600"/>
        <!-- 同ehcache参数maxElementsInMemory -->
        <property name="maxEntriesLocalHeap" value="1000"/>
        <!-- 同ehcache参数maxElementsOnDisk -->
        <property name="maxEntriesLocalDisk" value="10000000"/>
        <property name="memoryStoreEvictionPolicy" value="LRU"/>
    </cache>
    <select id="getUserInfo" resultType="bean.UsersInfo" useCache="true">
        select * from userinfo
        where userid = #{userId}
        <!--test:判断表达式(OGNL)-->
        <!--详情参考文档
            从参数取值中进行判断

            遇见特殊符号应该去写转义字符:
            &&:&amp;&amp;
        -->
        <if test="userName!=null &amp;&amp; userName!=&quot;&quot;">
            and username = #{userName}
        </if>


    </select>
</mapper>

4.千万不要忘了开启二级缓存(默认是开启的)和相应类如果要存入本地磁盘要序列化


public class UsersInfo implements Serializable {
    private static final long serialVersionUID = 1L;
    private Integer userId;
    private String userName;
    private String passWords;

    public UsersInfo(){

    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer id) {
        this.userId = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassWords() {
        return passWords;
    }

    public void setPassWords(String passWords) {
        this.passWords = passWords;
    }

    @Override
    public String toString() {
        return "UsersInfo{" +
                "id=" + userId +
                ", userName='" + userName + '\'' +
                ", passWords='" + passWords + '\'' +
                '}';
    }
}

config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings><!--控制台可以输出sql语句-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <setting name="cacheEnabled" value="true"/><!--开启二级缓存,本身是默认开启的-->
    </settings>
    <environments default="development"> <!--development:开发模式-->
        <environment id="development">
            <transactionManager type="JDBC"/>
            <!--配置数据库连接信息-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/db1?characterEncoding=utf8&amp;useSSL=false&amp;serverTimezone=UTC&amp;rewriteBatchedStatements=true"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers><!--加载所有的xml文件-->
        <mapper resource="mapper/UsersInfoMapper.xml"></mapper>
    </mappers>
</configuration>

5.测试

public class CacheTest{

    public static void main(String[] args){
        testSecondLevelCache();
    }

  
   
    public static void testSecondLevelCache(){
        SqlSession session1 = SessionUtil.ssf.openSession();
        SqlSession session2 = SessionUtil.ssf.openSession();
        UsersInfoMapper uim1 = session1.getMapper(UsersInfoMapper.class);
        UsersInfoMapper uim2 = session2.getMapper(UsersInfoMapper.class);
        UsersInfo ui = new UsersInfo();
        ui.setUserId(2);
        List<UsersInfo> list1 = uim1.getUserInfo(ui);
        for (UsersInfo usersInfo : list1) {
                System.out.println(usersInfo);
        }
        session1.close();//关掉
        //第二次查询是从二级缓存中拿到的数据,并没有发送新的sql
        List<UsersInfo> list2 = uim2.getUserInfo(ui);
        for (UsersInfo usersInfo : list2) {
            System.out.println(usersInfo);
        }
        session2.close();//关掉
    }
}

6.结果
在这里插入图片描述

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值