Table of contents
1. Introduction to Spring Cache
1. Common annotations for Spring Cache
2. Spring Cache uses redis caching steps
1. Introduction to Spring Cache
Spring cache is a framework that implements annotation-based caching functions. You only need to simply add an annotation to implement caching.
Function. Spring Cache provides a layer of abstraction, and the bottom layer can switch different cache implementations. Specifically, CacheManager
Interface to unify different caching technologies.
CacheManager is an abstract interface for various caching technologies provided by Spring.
Different CacheManagers need to be implemented for different caching technologies:
CacheManager | describe |
EhcachecacheManager | Using EhCache as caching technology |
GuavaCacheManager | Using Google's GuavaCache as caching technology |
RedisCacheManager | Using Redis as caching technology |
1. Common annotations for Spring Cache
annotation | illustrate |
@EnableCaching | Enable cache annotation function |
@Cacheable | Before the method is executed, spring first checks whether there is data in the cache. If there is data, it returns the cached data directly. If there is no data, it calls the method and puts the method return value in the cache. |
@CachePut | Put the return value of the method into the cache |
@CacheEvict | Delete one or more pieces of data from the cache |
In the spring boot project, to use caching technology, you only need to import the dependency package of the relevant caching technology into the project and use it on the startup class
@EnableCaching can enable caching support.
For example, to use Redis as the caching technology, you only need to import the maven coordinates of Spring data Redis.
2. Spring Cache uses redis caching steps
1. Add dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2. Add configuration
spring
redis:
host: 172.17.2.94 #ip地址
port: 6379 #端口
password: root@123456 #redis密码
database: 0 #指定数据库
cache:
redis:
time-to-live: 1800000 #设置缓存过期时间,可选
3. Use annotations
Annotate the startup class: @EnableCaching
@Slf4j
@SpringBootApplication
@EnableCaching
public class CacheDemoApplication {
public static void main(String[] args) {
SpringApplication.run(CacheDemoApplication.class,args);
log.info("项目启动成功...");
}
}
Annotation @CachePut: Put the method return value into the cache
/**
* CachePut:将方法返回值放入缓存
* value:缓存的名称,每个缓存名称下面可以有多个key
* key:缓存的key
*/
//@CachePut(value = "userCache",key = "#result.id")//result带表返回值
@CachePut(value = "userCache",key = "#user.id")//可以直接获取参数,参数名要保持一致
@PostMapping
public User save(User user){
userService.save(user);
return user;
}
key supports Spring's expression language, which can dynamically calculate the key value and obtain it through #, usually using direct #+ parameters
result: represents the return value, you can get the key by getting the return value
Annotation @CacheEvict: clean the specified cache
/**
* CacheEvict:清理指定缓存
* value:缓存的名称,每个缓存名称下面可以有多个key
* key:缓存的key
*/
@CacheEvict(value = "userCache",key = "#p0")//p固定写法,0表示下表,第一个参数
//@CacheEvict(value = "userCache",key = "#root.args[0]")//固定写法,0表示下表,第一个参数
//@CacheEvict(value = "userCache",key = "#id")//直接获取参数
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id){
userService.removeById(id);
}
//@CacheEvict(value = "userCache",key = "#p0.id")//p0第一个参数,id参数的属性
//@CacheEvict(value = "userCache",key = "#user.id")//直接获取参数属性
//@CacheEvict(value = "userCache",key = "#root.args[0].id")//获取第一个参数,id参数的属性
@CacheEvict(value = "userCache",key = "#result.id")//从返回值获取
@PutMapping
public User update(User user){
userService.updateById(user);
return user;
}
Annotation @Cacheable: Before the method is executed, spring first checks whether there is data in the cache. If there is data, it directly returns the cached data. If there is no data, it calls the method and puts the method return value in the cache.
/**
* Cacheable:在方法执行前spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,调用方法并将方法返回值放到缓存中
* value:缓存的名称,每个缓存名称下面可以有多个key
* key:缓存的key
* condition:条件,满足条件时才缓存数据
* unless:满足条件则不缓存
*/
@Cacheable(value = "userCache",key = "#id",unless = "#result == null")
@GetMapping("/{id}")
public User getById(@PathVariable Long id){
User user = userService.getById(id);
return user;
}
@Cacheable(value = "userCache",key = "#user.id + '_' + #user.name")//动态拼接key
@GetMapping("/list")
public List<User> list(User user){
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(user.getId() != null,User::getId,user.getId());
queryWrapper.eq(user.getName() != null,User::getName,user.getName());
List<User> list = userService.list(queryWrapper);
return list;
}