Mybatis学习(15)查询缓存之ehcache二级缓存

Mybatis并不擅长缓存数据,因此引入了第三方缓存产品。

如何使用ehcache来进行缓存呢?

一、导入jar包

https://github.com/mybatis/ehcache-cache/releases

这里有两个jar包,一个是ehcache的核心jar包,另外一个是mybatis与ehcache整合的jar包。

二、添加ehcache.xml文件

将解压之后的文件夹中,有一个ehcache.xml文件,直接放在src目录下面。

三、ehcache.xml文件详解

我们将注释删去,就只剩下如下的代码

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
    <diskStore path="java.io.tmpdir"/>
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </defaultCache>
</ehcache>

1、<diskStore/>标签

指定一个文件目录,当内存空间不够,需要将二级缓存的数据写到硬盘上时,会写到这个目录。默认是java.io.tmpdir。

这个默认的文件临时目录在哪呢?我们可以通过java代码来获取。

     @Test
	public void testEhcache(){
		String path=System.getProperty("java.io.tmpdir");
		System.out.println(path);
	}

看控制台输出:

2、<defaultCache/>标签

<defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </defaultCache>
  • maxElementInMemory:指定这个缓冲区可以存放缓存对象的最多个数
  • eternal:设置缓存对象是否会过期。默认为true,标示对象永远不会过期,此时下面两个设置默认为false
  • timeToIdleSeconds:设置允许对象处于空闲状态的最长时间,以秒为单位。
  • timeToLiveSeconds:设置对象在缓存中存活的最长时间,当对象超过这个时间之后,就会过期,ehCache就会把它从缓存中清除出去。设置为0的时候,表示可以无限期的存在于缓存中。
  • maxElementsOnDisk:指定硬盘缓冲区可以存放缓存对象的最多个数。
  • diskExpiryThreadIntervalSeconds:指定硬盘中缓冲对象的失效时间间隔
  • memoryStoreEvictionPolicy:如果内存缓冲区超过限制,那么将才去的替换算法。有三种FIFO、LFU、LRU。

四、使用ehcache缓存机制

1、在mapper映射文件声明缓存

在这里也可以对此mapper进行设置

这是因为一个项目当中会有很多个mapper文件,不同的mapper文件有不同的namespace,那么我们就可以在这个cache来设置不同的个性换设置

2、测试类

//根据id号选出学生
	@Test
	public void testselectStudentById() {
		//第一次查询
		sqlSession = MybatisUtil.getSqlSession();
		dao = sqlSession.getMapper(IStudentDao.class);
		Student student = dao.selectStudentById(24);	
		System.out.println(student);
		
		//关闭SqlSession
		sqlSession.close();
		
		//增加一个删除操作
		sqlSession = MybatisUtil.getSqlSession();
		dao = sqlSession.getMapper(IStudentDao.class);
		dao.deleteStuById(37);
	
		//第二次查询
		sqlSession = MybatisUtil.getSqlSession();
		dao = sqlSession.getMapper(IStudentDao.class);
		Student student2 = dao.selectStudentById(24);	
		System.out.println(student2);
		
	}

查看结果:

从结果我们可以看到,增删改操作对缓存没有影响,在两次查询当中只执行了一次select语句

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值