1.开启
@EnableCaching
2.添加依赖
<!--开启 cache 缓存 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>3.8.1</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>net.sf.ehcache</groupId>-->
<!-- <artifactId>ehcache</artifactId>-->
<!-- <version>2.10.6</version>-->
<!-- </dependency>-->
3.添加配置参数application.properties
spring.cache.ehcache.config= classpath:ehcache.xml
也可以直接在Application.java上使用注解
@ImportResource(locations = {"classpath:ehcache.xml"})
4.添加ehcache.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://www.ehcache.org/ehcache.xsd"
updateCheck="false">
<!--timeToIdleSeconds 当缓存闲置n秒后销毁 -->
<!--timeToLiveSeconds 当缓存存活n秒后销毁 -->
<!-- 缓存配置
name:缓存名称。
maxElementsInMemory:缓存最大个数。
eternal:对象是否永久有效,一但设置了,timeout将不起作用。
timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。 diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
maxElementsOnDisk:硬盘最大缓存个数。
diskPersistent:是否缓存虚拟机重启期数据 Whether the disk
store persists between restarts of the Virtual Machine. The default value
is false.
diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。 memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是
LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
clearOnFlush:内存数量最大时是否清除。 -->
<!-- 磁盘缓存位置 -->
<diskStore path="java.io.tmpdir" />
<!-- 默认缓存 -->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap" />
</defaultCache>
<!-- 测试 -->
<cache name="books"
eternal="false"
timeToIdleSeconds="2400"
timeToLiveSeconds="2400"
maxEntriesLocalHeap="10000"
maxEntriesLocalDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
overflowToDisk="true"
memoryStoreEvictionPolicy="LRU">
</cache>
</ehcache>
5.代码修改
在需要的方法上添加类似这样的注解.
查询方法:@Cacheable
保存或者更新方法:@CachePut
删除方法:@CacheEvict
@Cacheable(cacheNames="books",key = "#root.targetClass.getSimpleName().concat(':').concat(#bookId)")
@CachePut(cacheNames="books",key = "#root.targetClass.getSimpleName().concat(':').concat(#book.id)")
@CacheEvict(cacheNames="books",key = "#root.targetClass.getSimpleName().concat(':').concat(#bookId)")
@Override
@Cacheable(cacheNames="books",key = "#root.targetClass.getSimpleName().concat(':').concat(#bookId)")
public Book findBook(String bookId) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("执行方法,不使用缓存:{}",bookId);
return new Book("1","Query","1");
}
@Override
@CachePut(cacheNames="books",key = "#root.targetClass.getSimpleName().concat(':').concat(#book.id)")
public Book savaBook(Book book) {
return book;
}
@Override
@CacheEvict(cacheNames="books",key = "#root.targetClass.getSimpleName().concat(':').concat(#bookId)")
public String deleteBook(String bookId) {
return bookId;
}
为了减少些代码,
比如
@Cacheable(cacheNames="books",
也可以在类上使用@CacheConfig注解,整个类都是这个缓存设置了.
@CacheConfig(cacheNames = "books")
代码已经上传,可以直接运行
https://gitee.com/johnnycode/cdlig-demo.git
xsd下载路径:
https://www.ehcache.org/ehcache.xsd