一、整合所需物料
mybatis自身的缓存较为简单,就是内存里存放了map,但是其提供了接口,只要是实现了其提供接口的任何实现,都可以用来作为替代品。
mybatis-ehcache : 这个是mybatis对ehcache的适配器包
ehcache : ehcache的核心包
slf4j依赖
二、整合步骤
- 引入ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
<!-- 指定一个文件目录,当EhCache把数据写到硬盘上时,将把数据写到这个文件目录下 -->
<diskStore path="ehcacheTmp"/>
<!-- 设定缓存的默认数据过期策略 -->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="10"
timeToLiveSeconds="20"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"/>
</ehcache>
- 在需要使用ehcache的mapper.xml上做配置
<cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache>
- 编写测试方法
@Test
public void testEhcache(){
SqlSession sqlSession = null;
try{
sqlSession = getSession();
EhcacheMapper mapper = sqlSession.getMapper(EhcacheMapper.class);
Employee e1 = mapper.testEhcache(1);
System.out.println(e1.getName());
System.out.println("第一次查询完成");
Employee e2 = mapper.testEhcache(1);
System.out.println("第二次查询完成");
boolean b1 = (e1 == e2);
System.out.println("e1和e2是否相等:" + b1);
}catch (Exception e){
e.printStackTrace();
}finally {
sqlSession.close();
}
}
- 结果查看
DEBUG [main] [net.sf.ehcache.Cache]- Initialised cache: com.hly.dao.EhcacheMapper
这一行可以看出,使用ehcache初始化了这个mapper接口。
DEBUG [main] [com.hly.dao.EhcacheMapper]- Cache Hit Ratio [com.hly.dao.EhcacheMapper]: 0.0
DEBUG [main] [org.apache.ibatis.transaction.jdbc.JdbcTransaction]- Opening JDBC Connection
DEBUG [main] [org.apache.ibatis.datasource.pooled.PooledDataSource]- Created connection 785271142.
DEBUG [main] [org.apache.ibatis.transaction.jdbc.JdbcTransaction]- Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@2ece4966]
DEBUG [main] [com.hly.dao.EhcacheMapper.testEhcache]- ==> Preparing: SELECT * FROM tbl_employee where id=?
DEBUG [main] [com.hly.dao.EhcacheMapper.testEhcache]- ==> Parameters: 1(Integer)
DEBUG [main] [com.hly.dao.EhcacheMapper.testEhcache]- <== Total: 1
Lingyu He
第一次查询完成
DEBUG [main] [com.hly.dao.EhcacheMapper]- Cache Hit Ratio [com.hly.dao.EhcacheMapper]: 0.0
第二次查询完成
e1和e2是否相等:true
DEBUG [main] [net.sf.ehcache.store.disk.Segment]- put added 0 on heap
DEBUG [main] [org.apache.ibatis.transaction.jdbc.JdbcTransaction]- Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@2ece4966]
DEBUG [main] [org.apache.ibatis.transaction.jdbc.JdbcTransaction]- Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@2ece4966]
DEBUG [main] [org.apache.ibatis.datasource.pooled.PooledDataSource]- Returned connection 785271142 to pool.
DEBUG [com%002ehly%002edao%002e%0045hcache%004dapper.data] [net.sf.ehcache.store.disk.Segment]- fault removed 0 from heap
DEBUG [com%002ehly%002edao%002e%0045hcache%004dapper.data] [net.sf.ehcache.store.disk.Segment]- fault added 0 on disk
从这些控制台日志可以看到只执行了一次sql查询,并且ehcache也在不停的工作。
网友评论