美文网首页
29.Spring Cache

29.Spring Cache

作者: 星野君 | 来源:发表于2022-05-14 17:10 被阅读0次

常用注解

  • @EnableCaching 开启缓存注解
  • @Cacheable 在方法执行前spring先查看缓存是否有数据,有数据之间返回,没有数据则将数据缓存
  • @CachePut 将方法的返回值放入缓存中
  • @CacheEvict 将一条或者多条数据从缓存中删除

一、spring cache使用redis缓存

  1. 导入坐标
        <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>
  1. 配置application.yml
spring:
  cache:
    redis:
      time-to-live: 1800000 #设置缓存有效期毫秒
  1. 在启动类上加上@EnableCaching,开启缓存注解功能
@SpringBootApplication
@EnableCaching
public class ReggieTakeOutApplication {

  public static void main(String[] args) {
    SpringApplication.run(ReggieTakeOutApplication.class, args);
    log.info("启动成功");
  }
}
  1. 在方法上加入@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)

相关文章

网友评论

      本文标题:29.Spring Cache

      本文链接:https://www.haomeiwen.com/subject/edfmurtx.html