使用springCache实现缓存
简介
这个springCache貌似jdk8或者以上才可以
- cache最好加在
controller
层,毕竟返回给前端的数据,在这一步才是最完整的,缓存controller的数据才有意义
配置
导入依赖
<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>
@EnableCaching // 开启缓存注解
@Slf4j
@SpringBootApplication
@EnableCaching // 开启缓存注解
public class CacheDemoApplication {
public static void main(String[] args) {
SpringApplication.run(CacheDemoApplication.class,args);
log.info("项目启动成功...");
}
}
配置一下redis
server:
port: 8888
spring:
datasource:
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/spring_cache_demo?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
username: root
password: root
redis:
host: localhost
port: 6379
database: 1
注解CachePut
key有两种写法
@PostMapping
@CachePut(cacheNames = "userCache",key = "#user.id") // 更新缓存 key的生成是 userCache::id 形参user.id
// @CachePut(cacheNames = "userCache",key = "#result.id") // 更新缓存 key的生成是 userCache::id 返回值id
public User save(@RequestBody User user){
userMapper.insert(user);
return user;
}
注解@Cacheable
查询缓存 key的生成是 userCache::id)(如果有缓存则直接返回缓存,没有则查询数据库,然后将查询结果缓存)
@GetMapping
@Cacheable(cacheNames = "userCache",key = "#id") // 查询缓存 key的生成是 userCache::id)(如果有缓存则直接返回缓存,没有则查询数据库,然后将查询结果缓存)
public User getById(Long id){
User user = userMapper.getById(id);
return user;
}
注解@CacheEvict
分为删除一个和删除所有
@DeleteMapping
@CacheEvict(cacheNames = "userCache",key = "#id") // 删除缓存 key是 userCache::id
public void deleteById(Long id){
userMapper.deleteById(id);
}
@DeleteMapping("/delAll")
@CacheEvict(cacheNames = "userCache",allEntries = true) // 删除缓存 key是 userCache::id
public void deleteAll(){
userMapper.deleteAll();
}