一、介绍
Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存。
二、使用
2.1、导包
<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.2.1</version>
</dependency>
2.2、在Mapper中指定使用ehcache缓存实现
2.3、在resource下新键ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<diskStore path="./tmpdir/Tmp_EhCache"/>
<defaultCache
eternal="false"
maxElementsInMemory="10000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="259200"
memoryStoreEvictionPolicy="LRU"/>
<cache
name="cloud_user"
eternal="false"
maxElementsInMemory="5000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="1800"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
2.4、测试
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
SqlSession sqlSession2 = MybatisUtils.getSqlSession();
UsersMapper mapper = sqlSession.getMapper(UsersMapper.class);
Users users = mapper.queryUsersById(1);
System.out.println(users);
sqlSession.close();
UsersMapper mapper2 = sqlSession2.getMapper(UsersMapper.class);
Users users2 = mapper2.queryUsersById(1);
System.out.println(users2);
System.out.println(users == users2);
sqlSession2.close();
}