第九章 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实现)
- ***************************************
概述
1. Ehcache 2.x 缓存
1.1 SpringBoot整合Ehcache缓存
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>
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>
java
spring.cache.ehcache.config=classpath:config/another-config.xml
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实现