SpringBoot集成Ehcache非常方便,也很简单,只需要以下简单4步即可实现Ehcache缓存。
第一步,增加两个依赖包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
第二步,增加ehcache.xml配置
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<diskStore path="java.io.tmpdir/Tmp_EhCache"/>
<defaultCache
eternal="false"
maxElementsInMemory="10000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="259200"
memoryStoreEvictionPolicy="LRU"/>
<cache
name="book"
eternal="false"
maxElementsInMemory="5000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="1800"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
ehcache.xml配置参数说明:
共三种标签:diskStore、defaultCache、cache
1、diskStore标签配置说明
属性名 | 属性值说明 | 属性含义 |
---|---|---|
path | user.home – 用户主目录 | 缓存路径 |
path | user.dir – 用户当前工作目录 | 缓存路径 |
path | java.io.tmpdir – 默认临时文件路径 | 缓存路径 |
2、defaultCache标签配置说明
属性名 | 属性值说明 | 属性含义 |
---|---|---|
maxElementsInMemory | 缓存最大数目 | |
maxElementsOnDisk | 硬盘最大缓存个数 | |
eternal | true、false | 对象是否永久有效,设置为true时,timeout将不起作用 |
overflowToDisk | true、false | 当系统宕机时是否保存到磁盘 |
timeToIdleSeconds | 默认值是0,可闲置时间无穷大 | 设置对象在失效前的允许闲置时间(单位:秒)。当eternal=false时使用。可选属性 |
timeToLiveSeconds | 默认值:0,对象存活时间无穷大 | 设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。当eternal=false时使用 |
diskPersistent | 默认为false | 虚拟机重启时,是否持久化数据到磁盘 |
diskSpoolBufferSizeMB | 默认是30MB | 设置DiskStore(磁盘缓存)的缓存区大小,每个Cache都有自己的一个缓冲区 |
diskExpiryThreadIntervalSeconds | 默认是120秒 | 磁盘失效线程运行时间间隔 |
memoryStoreEvictionPolicy | 默认策略是LRU(最近最少使用) | 当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存 ,三种策略:FIFO、LFU、LRU |
clearOnFlush | 内存数量最大时是否清除 |
FIFO:first in first out,先进先出。
LFU:Less Frequently Used,最少被使用。缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
LRU:Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
3、 cache标签配置说明
cache标签属性包括了defaultCache中的属性,但多一个name属性,name属性是缓存名称,对应@Cacheable注解中的value。
第三步,Ehcache注入Bean,编写EhcacheConfiguration类,如下:
package com.sam.study.config;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
@Configuration
@EnableCaching
public class EhcacheConfiguration {
@Bean
public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() {
EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean();
ehCacheManagerFactoryBean.setConfigLocation(new ClassPathResource("/config/ehcache.xml"));
return ehCacheManagerFactoryBean;
}
@Bean
public EhCacheCacheManager ehCacheCacheManager(EhCacheManagerFactoryBean ehCacheManagerFactoryBean) {
EhCacheCacheManager ehCacheCacheManager = new EhCacheCacheManager(ehCacheManagerFactoryBean.getObject());
return ehCacheCacheManager;
}
}
第四步,配置@Cacheable注解,service类代码示例如下:
package com.sam.study.service;
import com.github.pagehelper.PageHelper;
import com.sam.study.bean.Book;
import com.sam.study.dao.BookMapper;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
@Service
public class BookServiceImpl implements IBookService {
@Resource
private BookMapper bookMapper;
@Cacheable(value = "book")
public List<Book> findAllBook(int pageNum, int pageSize) {
System.out.println("findAllBook...................");
PageHelper.startPage(pageNum, pageSize);
Iterable<Book> iterable = bookMapper.selectAll();
List<Book> bookList = new ArrayList<>();
iterable.forEach(book -> bookList.add(book));
return bookList;
}
@Override
@Cacheable(value = "book", key = "#id")
public Book findBookById(int id) {
System.out.println("findBookById从数据库查询:" + id);
return bookMapper.selectById(id);
}
}
以上四步即实现ehcache缓存。
最后,补充@Cacheable注解的两个基本属性说明:
1、cacheNames和value
这两个属性都是指定缓存的名字,通过源码可以看出将返回结果放在哪个缓存中,可以指定多个缓存。
2、key
缓存数据使用的key,它是用来指定对应的缓存,可以模拟使用方法参数值作为key的值,也可以使用SpEL表达式的值来指定。
名称 | 描述 | 示例 |
---|---|---|
methodName | 被调用的方法名称 | #root.methodName |
Method | 被调用的方法 | #root.method.name |
Target | 当前被调用的目标对象 | #root.target |
targetClass | 当前被调用的目标对象类 | #root.targetClass |
args | 被调用方法的参数列表 | root.args[0] |
caches | 调用的缓存列表 | root.caches[0].name |
argument name | 方法的参数名称,可以直接使用#参数名 | #id,#name等等 |
result | 执行方法后的返回值 | #result |
也可以通过以下方式查看root object对象有哪些:
本文主要是分享SpringBoot集成Ehcache实现缓存的基本使用。关于@Cacheable注解的深入探讨,后续再另写博文分享。谢谢!!