缓存的作用
- 缓存是一种介于数据永存存储介质与数据应用之间的数据临时存储介质
- 使用缓存可以有效的减少低速数据读取过程的次数,提高系统性能
Spring缓存使用方式
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
@EnableCaching
@SpringBootApplication
// 开启缓存功能
@EnableCaching
public class CacheApplication {
public static void main(String[] args) {
SpringApplication.run(CacheApplication.class, args);
}
}
@Cacheable 注解就可以将运行结果缓存,以后查询相同的数据,直接从缓存中取,不需要调用方法
cacheNames:用来指定缓存组件的名字
key:缓存数据时使用的 key (#id表示取出参数id的值作为key)
@Cacheable(value = "cacheSpace", key = "#id")
public Book getById(Integer id) {
return bookDao.selectById(id);
}
@CacheEvict
@CacheEvict(value = "userCache", key = "#id")
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id){
userService.removeById(id);
}
@CacheEvict(value = "cacheSpace", key = "@user.id")
@PutMapping
public User update(User user){
userService.updateById(user);
return user;
}