8.10 用redis实现缓存功能和Spring Cache

什么是缓存?

缓存(Cache), 就是数据交换的缓冲区,俗称的缓存就是缓冲区内的数据,一般从数据库中获取,存储于本地代码。

通过Redis来缓存数据,减少数据库查询操作;

逻辑
每个分类的菜品保存一份缓存数据
数据库菜品数据有变更时清理缓存数据

如何将商品数据缓存起来。

bash 复制代码
   @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<DishVO>> list(Long categoryId) {

        //查询redis里面是否存在数据类;
    String key="dish_"+categoryId;
        //如果存在直接返回
        List<DishVO> list = (List<DishVO>) redisTemplate.opsForValue().get(key);

     if (list!=null&&list.size()>0){
         return Result.success(list);
     }
        //不存在需要查询数据库,并保存至redis里面
        Dish dish = new Dish();
        dish.setCategoryId(categoryId); //设置套餐的id

        dish.setStatus(StatusConstant.ENABLE);//查询起售中的菜品

         list = dishService.listWithFlavor(dish);

        redisTemplate.opsForValue().set(key,list); //将他缓存起来
        return Result.success(list);

    }

控制台没有sql了,说明缓存已经实现了。

二 数据内容发生改变的时候,需要修改redis的内容。

修改操作、删除菜品、起售或者停售、新建菜品也需要缓存数据

bash 复制代码
private void  cleanCache(String pattern){

        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys); //支持删除集合的

    }

删除对应的缓存数据

缓存套餐功能

spring Cache 实现了基于注解的缓存功能

bash 复制代码
   <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>

对应的maven坐标

注解开发

Cacheable 在方法执行前查询缓存是否有数据;

相关推荐
万物皆字节20 小时前
【避坑】使用CacheEvict需要注意的坑
redis
xbgRS20 小时前
spring整合mybaits
java·spring·mybatis
ruleslol20 小时前
静态依赖注入 VS 动态依赖查询
spring
墨雨晨曦881 天前
Spring AI总结
java·人工智能·spring
用户3126874877201 天前
Spring Boot 异常处理到底怎么玩的?从 DispatcherServlet 到全局兜底的全链路拆解
spring
不才不才不不才1 天前
Spring 源码系列(17): HandlerMapping 与 HandlerAdapter 两大体系
java·后端·spring
(轻舟已过万重山)1 天前
第40章 Spring AI 实战:企业级 AI 应用架构
人工智能·spring·架构
范什么特西2 天前
回答知识总结04(redis)
数据库·redis·缓存
math_hongfan2 天前
鸿蒙离线数据缓存高级架构:弱网预加载/离线数据优先级/同步冲突解决/上线后数据合并策略
学习·缓存·华为·架构·harmonyos·鸿蒙
堕落年代2 天前
Ollama CPU 推理大提示词优化实测报告(细致化数据版)
java·后端·spring