常用注解
- @EnableCaching 开启缓存注解
- @Cacheable 在方法执行前spring先查看缓存是否有数据,有数据之间返回,没有数据则将数据缓存
- @CachePut 将方法的返回值放入缓存中
- @CacheEvict 将一条或者多条数据从缓存中删除
一、spring cache使用redis缓存
- 导入坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
- 配置application.yml
spring:
cache:
redis:
time-to-live: 1800000 #设置缓存有效期毫秒
- 在启动类上加上@EnableCaching,开启缓存注解功能
@SpringBootApplication
@EnableCaching
public class ReggieTakeOutApplication {
public static void main(String[] args) {
SpringApplication.run(ReggieTakeOutApplication.class, args);
log.info("启动成功");
}
}
- 在方法上加入@Cacheable,@CachePut等注解进行缓存操作
@Cacheable(value = "setmealCache", key = "#setmeal.id")
@Override
public List<Setmeal> list(Setmeal setmeal) {
final LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper();
lqw.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
lqw.eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus());
lqw.orderByDesc(Setmeal::getUpdateTime);
final List<Setmeal> setmeals = setmealMapper.selectList(lqw);
return setmeals;
}
删除所有缓存数据
@CacheEvict(value = "setmealCache", allEntries = true)
网友评论