第九章 SpringBoot缓存-方法的缓存
- 概述
- [1. Ehcache 2.x 缓存](#1. Ehcache 2.x 缓存)
-
- [1.1 SpringBoot整合Ehcache缓存](#1.1 SpringBoot整合Ehcache缓存)
- [1.2 应用:缓存方法](#1.2 应用:缓存方法)
-
- [缓存方法注解的使用 ❤❤❤](#缓存方法注解的使用 ❤❤❤)
- [2. Redis实现](#2. Redis实现)
- ***************************************
概述
![](https://file.jishuzhan.net/article/1785490533733371906/002f425d46ee8fe1b94c3e00e80a017d.webp)
1. Ehcache 2.x 缓存
1.1 SpringBoot整合Ehcache缓存
![](https://file.jishuzhan.net/article/1785490533733371906/23820302b908991de10b11e3e59e84b2.webp)
java
<dependency>
<groupId>org. springframework. boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactid>ehcache</artifactid>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactid>spring-boot-starter-web</artifactid>
</dependency>
![](https://file.jishuzhan.net/article/1785490533733371906/65200d657a3c1c2bbcf7e1b9406e2f78.webp)
xml
<ehcache>
<diskStore path="java.io.tmpdir/cache"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="false"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
/>
<cache name="book_cache"
maxElementsInMemory="10000"
eternal="true"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
diskPersistent="true"
diskExpiryThreadIntervalSeconds="600"
/>
</ehcache>
![](https://file.jishuzhan.net/article/1785490533733371906/d15ea71d9fc8b2b14fe4e14b7468650e.webp)
java
spring.cache.ehcache.config=classpath:config/another-config.xml
![](https://file.jishuzhan.net/article/1785490533733371906/6adfde6a56cbadd74eaadc8797b117a7.webp)
1.2 应用:缓存方法
缓存方法注解的使用 ❤❤❤
java
@Repository
@CacheConfig(cacheNames ="book_cache")
public class BookDao {
@Cacheable
public Book getBookById(Integer id){
System.out.println("getBookById");
Book book = new Book();
book.setId(id);
book.setName("三国演义");
book.setAuthor("罗贯中");
return book;
}
@CachePut(key ="#book.id")
public Book updateBookById(Book book){
System.out.println("updateBookById");
book.setName("三国演义2");
return book;
}
@CacheEvict(key ="#id")
public void deleteBookById(Integer id){
System.out.println("deleteBookById");
}
}
自定义缓存key生成器
如果这些key不能够满足开发需求,开发者也可以自定义缓存key的生成器KeyGenerator,
代码如下:
java
@Component
public class MyKeyGenerator implements KeyGenerator {
@Override
public Object generate(Object target,Method method,object... params){
return Arrays.tostring(params);
}
}
2. Redis实现
![](https://file.jishuzhan.net/article/1785490533733371906/ab1874d93b8816a0096ef716c701267c.webp)