MyBatis使用Ehcache实现二级缓存

最近在探寻 MyBatis 持久层框架,发现入门简单,但是随着满足各种需求的增加,MyBatis 的功能也让人眼花缭乱。今天写笔记来记录下一个第三方缓存框架 Ehcache 和 MyBatis 的简单配合使用,来实现数据缓存。

一、Ehcache 简介

Ehcache 是一种广泛使用的开源 Java 分布式缓存。具有快速简单低消耗依赖性小扩展性强支持对象或序列化缓存支持缓存或元素的失效提供 LRU / LFU / FIFO 缓存策略支持内存缓存和磁盘缓存分布式缓存机制等等特点。    Ehcache 作为开放源代码项目,采用限制比较宽松的 Apache License V2.0 作为授权方式,被广泛地用于 Hibernate、Spring、Cocoon 等其他开源系统。Ehcache 从 Hibernate 发展而来,逐渐涵盖了 Cahce 界的全部功能,是目前发展势头最好的一个项目。

MyBatis 和 Ehcache 整合框架下载地址:https://github.com/mybatis/ehcache-cache

Ehcache 缓存框架整合的文档地址:http://www.mybatis.org/ehcache-cache/

二、Ehcache 文件配置

1. Maven 工程配置 pom.xml 导入 jar 包

MyBatis 和 Ehcache 整合架包

<dependency>
    <groupId>org.mybatis.caches</groupId>
    <artifactId>mybatis-ehcache</artifactId>
    <version>1.1.0</version>
</dependency>

因为 Ehcache 的依赖 slf4j 这个日志的 jar 包,会和 log4j 的 jar 包冲突,导致日志不能显示了,解决办法就整合他们,导入联合 jar 包,所以还要一个依赖

<dependency>
	<groupId>org.slf4j</groupId>
	<artifactId>slf4j-log4j12</artifactId>
	<version>1.7.25</version>
	<scope>test</scope>
</dependency>

2. 配置步骤

① 创建 ehcache.xml 文件

<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
	<!-- mac 电脑, 跟 win 设置路径有点不一样 示例: path="d:/ehcache/" -->
	<diskStore path="${user.home}/Downloads/ehcache" />

	<!-- 默认缓存配置 没有特别指定就用这个配置 -->
	<defaultCache maxElementsInMemory="10000"
				  eternal="false"
				  timeToIdleSeconds="3600" <!--1 hour-->
				  timeToLiveSeconds="3600" <!--1 hour-->
				  overflowToDisk="true"
				  maxElementsOnDisk="10000000"
				  diskPersistent="false"
				  memoryStoreEvictionPolicy="LRU"
				  diskExpiryThreadIntervalSeconds="120" />
</ehcache>

② 在 MyBatis 配置文件中开启二级缓存配置

<settings>
	<setting name="cacheEnabled" value="true" />
</settings>

③ 在 Mapper 配置文件中开启缓存,添加 Ehcache 缓存

<mapper namespace="com.ogemray.dao.StudentDao">
  <cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
  ...
</mapper>

④ 缓存实体类要实现 Serializable 接口

public class Student implements Serializable

3. Ehcache 配置标签和属性说明