Spring Cache是一个框架,实现了基于注解的缓存功能,只需要简单地加一个注解,就能实现缓存功能。
一、Spring Cache提供了一层抽象,底层可以切换不同的缓存实现(只需要添加下载相关的jar包就可以切换不同的缓存实现),例如:
- EHCache
- Caffeine
- Redis
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
<version>2.7.3</version>
</dependency>
二、Spring Cache
常用注解:{ @Cacheable(可放可取)@CachePut(只有可放进缓存)}
三、实践
1、在启动类中加入@EnableCaching注解,其作用:开启缓存注解功能
@Slf4j
@SpringBootApplication
@EnableCaching//开启缓存注解功能
public class CacheDemoApplication {
public static void main(String[] args) {
SpringApplication.run(CacheDemoApplication.class,args);
log.info("项目启动成功...");
}
}
2、在controller中,@Cacheput的使用,详解看代码
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
@Autowired
private UserMapper userMapper;
/*
* 新增一个用户
* */
@PostMapping
//生成 key value 于 缓存之中
@CachePut(cacheNames = "userCache",key = "#user.id") //如果使用Spring Cache缓存数据,key的生成:userCache::2(常用)
//@CachePut(cacheNames="userCache",key="#result.id")/对象导航
//@CachePut(cacheNames "userCache",key "#p0.id")//p0指的就是user这个参数
//@CachePut(cacheNames "userCache",key "#a0.id")//a0同上
//@CachePut(cacheNames "userCache",key "#root.args[0].id")
public User save(@RequestBody User user){
userMapper.insert(user);
return user;
}
}
运行结果:
3、@Cacheable注解的使用((cacheNames = "userCache",key = "#id"))
/*
* 通过id查询用户
* */
@GetMapping
//在方法执行前先查询缓存中是否有数据,如果有数据,则直接返回缓存数据;
//如果没有缓存数据,调用方法 查找数据库的数据 并将方法返回值放到缓存中
@Cacheable(cacheNames = "userCache",key = "#id")//key的生成:userCache::2
public User getById(Long id){
User user = userMapper.getById(id);
return user;
}
4、 @CacheEvict(将一条或多条数据从缓存中删除)
@DeleteMapping
@CacheEvict(cacheNames = "userCache",key = "#id")//key的生成:userCache::2
public void deleteById(Long id){
userMapper.deleteById(id);
}
@DeleteMapping("/delAll")
@CacheEvict(cacheNames = "userCache",allEntries = true)//删除所有用: allEntries = true
public void deleteAll(){
userMapper.deleteAll();
}