EHCache缓存针对于MyBatis的二级缓存。
MyBatis默认二级缓存是SqlSessionFactory级别的。

添加依赖

<!-- MyBatis-EHCache整合包 -->
<dependency>
	<groupId>org.mybatis.caches</groupId>
	<artifactId>mybatis-ehcache</artifactId>
	<version>1.2.1</version>
	<!-- 排除冲突包 -->
	<exclusions>
		<exclusion>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
		</exclusion>
	</exclusions>
</dependency>
<!-- SLF4j日志接口的实现类 -->
<dependency>
	<groupId>ch.qos.logback</groupId>
	<artifactId>logback-classic</artifactId>
	<version>1.4.11</version>
	<scope>test</scope>
</dependency>

创建EHCache的配置文件ehcache.xml

配置文件名必须为ehcache.xml

<?xml version="1.0" encoding="utf-8" ?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
    <!-- 本地磁盘保存路径 -->
    <diskStore path="D:\ehcache"/>
    <!-- 默认缓存设置 -->
    <defaultCache
            maxElementsInMemory="1000"
            maxElementsOnDisk="10000000"
            eternal="false"
            overflowToDisk="true"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
    </defaultCache>
</ehcache>
EHCache配置文件的配置项说明

image

创建logback日志文件

使用SLF4J日志时,log4j日志文件会失效,需要配置SLF4J的具体实现logback来打印日志。
创建logback的配置文件logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
    <!-- 指定日志输出的位置 -->
    <appender name="STDOUT"
        class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
        <!-- 日志输出的格式 -->
        <!-- 按照顺序分别是:时间、日志级别、线程名称、打印日志的类、日志主体内容、换行-->
        <pattern>[%d{HH:mm:ss.SSS}] [%-5level] [%thread] [%logger]
        [%msg]%n</pattern>
        </encoder>
    </appender>
    <!-- 设置全局日志级别。日志级别按顺序分别是:DEBUG、INFO、WARN、ERROR -->
    <!-- 指定任何一个日志级别都只打印当前级别和后面级别的日志。 -->
    <root level="DEBUG">
    <!-- 指定打印日志的appender,这里通过“STDOUT”引用了前面配置的appender -->
        <appender-ref ref="STDOUT" />
    </root>
    <!-- 根据特殊需求指定局部日志级别 -->
    <logger name="com.evan.mybatis.mapper" level="DEBUG"/>
</configuration>

mapper.xml设置二级缓存的类型

<!-- 使用Ehcache缓存作为二级缓存 -->
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>

测试

public class CacheTest {

    private static final Logger LOGGER = LoggerFactory.getLogger(CacheTest.class);

    @Test
    public void test2() {
        try {
            //读取MyBatis核心配置文件中的信息
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            //通过SqlSessionFactory创建SqlSession对象
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

            SqlSession sqlSession1 = sqlSessionFactory.openSession(true);
            SqlSession sqlSession2 = sqlSessionFactory.openSession(true);

            CacheMapper mapper1 = sqlSession1.getMapper(CacheMapper.class);
            List<Emp> emps1 = mapper1.getEmpByDeptId(1);
            emps1.forEach(System.out::println);
            //关闭sqlSession的时候才会把保存在一级缓存中的数据保存到二级缓存中
            sqlSession1.close();

            CacheMapper mapper2 = sqlSession2.getMapper(CacheMapper.class);
            List<Emp> emps2 = mapper2.getEmpByDeptId(1);
            emps2.forEach(System.out::println);
            //关闭sqlSession的时候才会把保存在一级缓存中的数据保存到二级缓存中
            sqlSession2.close();
        } catch (IOException e) {
            LOGGER.error("测试方法:test2异常:{0}",e);
        }
    }
}

输出结果:
image