外卖项目day10---缓存商品/Spring Cache初学、购物车功能

news2024/9/9 6:15:35

缓存菜品,只需要在DishController中修改一下代码即可


/**
 * 菜品管理
 */
@RestController
@RequestMapping("/admin/dish")
@Api(tags = "菜品相关接口")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 新增菜品
     * @param dishDTO
     * @return
     */
    @PostMapping
    @ApiOperation("新增菜品")
    public Result save(@RequestBody DishDTO dishDTO){
        log.info("新增菜品:{}",dishDTO);
        dishService.saveWithFlavor(dishDTO);


        //清楚缓存数据
        String key = "dish_" + dishDTO.getCategoryId();
        cleanCache(key);
        return Result.success();
    }

    /**
     *
     * @return
     */
    @GetMapping("/page")
    @ApiOperation("菜品分页查询")
    public Result<PageResult> page(DishPageQueryDTO dishPageQueryDTO){
        log.info("菜品分页查询:{}",dishPageQueryDTO);
        PageResult pageResult = dishService.pageQuery(dishPageQueryDTO);
        return Result.success(pageResult);
    }

    /**
     * 菜品批量删除
     * @param ids
     * @return
     */
    @DeleteMapping
    @ApiOperation("菜品批量删除")
    public Result delete(@RequestParam List<Long> ids){
        log.info("菜品批量删除:{}",ids);
        dishService.deleteBatch(ids);


        //将所有的菜品缓存数据清理掉,所有以dish_开头的key
        cleanCache("dish_*");
        return Result.success();
    }

    /**
     * 根据id查询菜品
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation("根据id查询菜品")
    public Result<DishVO> getById(@PathVariable Long id){
        log.info("根据id查询菜品:{}",id);
        DishVO dishVO = dishService.getByIdWithFlavor(id);
        return Result.success(dishVO);
    }

    /**
     * 修改菜品
     * @param dishDTO
     * @return
     */
    @PutMapping
    @ApiOperation("修改菜品")
    public Result update(@RequestBody DishDTO dishDTO){
        log.info("修改菜品:{}",dishDTO);
        dishService.updateWithFlavor(dishDTO);


        //将所有的菜品缓存数据清理掉,所有以dish_开头的key
        cleanCache("dish_*");

        return Result.success();
    }

    /**
     * 菜品起售停售
     * @param status
     * @param id
     * @return
     */
    @PostMapping("/status/{status}")
    @ApiOperation("菜品起售停售")
    public Result startOrStop(@PathVariable Integer status,Long id){
        log.info("菜品起售停售:{},{}",status,id);
        dishService.startOrStop(status,id);


        //将所有的菜品缓存数据清理掉,所有以dish_开头的key
        cleanCache("dish_*");

        return Result.success();
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<Dish>> list(Long categoryId){
        List<Dish> list = dishService.list(categoryId);
        return Result.success(list);
    }

    /**
     * 清理缓存数据
     * @param pattern
     */
    private void cleanCache(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }
}

缓存套餐

用到Spring Cache,如果不会的话请看我这篇文章

Spring Cache常用注解-CSDN博客

1、导入Spring Cache 和Redis相关的maven坐标

        <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>

2、在启动类上加入@EnableCaching注解,开启缓存注解功能

@SpringBootApplication
@EnableTransactionManagement //开启注解方式的事务管理
@Slf4j
@EnableCaching //开启缓存注解功能
public class SkyApplication {
    public static void main(String[] args) {
        SpringApplication.run(SkyApplication.class, args);
        log.info("server started");
    }
}

3、在用户端接口SetmealController的list 方法上加入@Cacheable注解

@RestController("userSetmealController")
@RequestMapping("/user/setmeal")
@Api(tags = "C端-套餐浏览接口")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;

    /**
     * 条件查询
     *
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("根据分类id查询套餐")
    @Cacheable(cacheNames = "setmealCache" , key = "#categoryId") //key : setmealCache::100
    public Result<List<Setmeal>> list(Long categoryId) {
        Setmeal setmeal = new Setmeal();
        setmeal.setCategoryId(categoryId);
        setmeal.setStatus(StatusConstant.ENABLE);

        List<Setmeal> list = setmealService.list(setmeal);
        return Result.success(list);
    }


4、在管理端接口SetmealController的 save、delete、update、startOrStop等方法上加入CacheEvict注解

 /**
     * 新增套餐
     * @param setmealDTO
     */
    @PostMapping
    @ApiOperation("新增套餐")
    @CacheEvict(cacheNames = "setmealCache" , key = "#setmealDTO.categoryId") //key : setmealCache::100
    public Result save(@RequestBody SetmealDTO setmealDTO){
        log.info("新增套餐:{}",setmealDTO);
        setmealService.saveWithDish(setmealDTO);
        return Result.success();
    }
 /**
     * 批量删除套餐
     * @param ids
     * @return
     */
    @DeleteMapping
    @ApiOperation("批量删除套餐")
    @CacheEvict(cacheNames = "setmealCache" , allEntries = true)
    public Result delete(@RequestParam List<Long> ids){
        log.info("批量删除套餐:{}",ids);
        setmealService.deleteBatch(ids);
        return Result.success();
    }
 /**
     * 修改套餐
     * @param setmealDTO
     */
    @PutMapping
    @ApiOperation("修改套餐")
    @CacheEvict(cacheNames = "setmealCache" , allEntries = true)
    public Result update(@RequestBody SetmealDTO setmealDTO){
        log.info("修改套餐:{}",setmealDTO);
        setmealService.update(setmealDTO);
        return Result.success();
    }
    /**
     * 套餐起售停售
     * @param status
     * @param id
     * @return
     */
    @PostMapping("/status/{status}")
    @ApiOperation("套餐起售停售")
    @CacheEvict(cacheNames = "setmealCache" , allEntries = true)
    public Result startOrStop(@PathVariable Integer status,Long id){
        log.info("套餐起售停售:{},{}",status,id);
        setmealService.startOrStop(status,id);
        return Result.success();
    }

测试:点击小程序,分类套餐,redis中也有了缓存数据

点击停售,redis的缓存数据全部删除 ,测试成功!

 

添加购物车

 ShoppingCartController代码

@RestController
@RequestMapping("/user/shoppingCart")
@Slf4j
@Api(tags = "C端购物车相关接口")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 添加购物车
     * @param shoppingCartDTO
     * @return
     */
    @PostMapping("/add")
    @ApiOperation("添加购物车")
    public Result add(@RequestBody ShoppingCartDTO shoppingCartDTO){
        log.info("添加购物车,商品信息为:{}",shoppingCartDTO);

        shoppingCartService.addShoppingCart(shoppingCartDTO);
        return Result.success();

    }
}

 ShoppingCartService接口代码

public interface ShoppingCartService {

    /**
     * 添加购物车
     * @param shoppingCartDTO
     */
    void addShoppingCart(ShoppingCartDTO shoppingCartDTO);
}

 ShoppingCartServiceImpl代码

@Service
@Slf4j
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 添加购物车
     * @param shoppingCartDTO
     */
    public void addShoppingCart(ShoppingCartDTO shoppingCartDTO) {
        //判断当前加入到购物车中的商品是否已经存在了
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);
        Long userId = BaseContext.getCurrentId();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);

        //如果已经存在了,只需要将数量加一
        if(list != null && list.size() > 0){
            ShoppingCart cart = list.get(0);
            cart.setNumber(cart.getNumber()+1); //update shopping_cart set number = ? where id = ?
            shoppingCartMapper.updateNumberById(cart);
        }else {
            //如果不存在,需要插入一条购物车数据

            //判断本次添加到购物车的是菜品还是套餐
            Long dishId = shoppingCartDTO.getDishId();
            if(dishId != null){
                //本次添加到购物车的是菜品
                Dish dish = dishMapper.getById(dishId);
                shoppingCart.setName(dish.getName());
                shoppingCart.setImage(dish.getImage());
                shoppingCart.setAmount(dish.getPrice());


            }else{
                //本次添加到购物车的是套餐
                Long setmealId = shoppingCartDTO.getSetmealId();
                Setmeal setmeal = setmealMapper.getById(setmealId);

                shoppingCart.setName(setmeal.getName());
                shoppingCart.setImage(setmeal.getImage());
                shoppingCart.setAmount(setmeal.getPrice());
            }
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.insert(shoppingCart);
        }
    }
}

 ShoppingCartMapper接口代码

@Mapper
public interface ShoppingCartMapper {

    /**
     * 动态条件查询
     * @param shoppingCart
     * @return
     */
    List<ShoppingCart> list(ShoppingCart shoppingCart);

    /**
     * 根据id修改商品数量
     * @param shoppingCart
     */
    @Update("update shopping_cart set number = #{number} where id = #{id} ")
    void updateNumberById(ShoppingCart shoppingCart);

    /**
     * 插入购物车数据
     * @param shoppingCart
     */
    @Insert("insert into shopping_cart (name, image, user_id, dish_id, setmeal_id, dish_flavor, amount, create_time) VALUES " +
            "(#{name},#{image},#{userId},#{dishId},#{setmealId},#{dishFlavor},#{amount},#{createTime})")
    void insert(ShoppingCart shoppingCart);
}

ShoppingCartMapper.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.sky.mapper.ShoppingCartMapper">


    <select id="list" resultType="com.sky.entity.ShoppingCart">
        select * from shopping_cart
        <where>
            <if test="userId != null">
                and user_id = #{userId}
            </if>
            <if test="setmealId != null">
                and setmeal_id = #{setmealId}
            </if>
            <if test="dishId != null">
                and dish_id = #{dishId}
            </if>
            <if test="dishFlavor != null">
                and dish_flavor = #{dishFlavor}
            </if>
        </where>
    </select>
</mapper>

查看购物车

ShoppingCartController代码 

    /**
     * 查看购物车
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("查看购物车")
    public Result<List<ShoppingCart>> list(){

        List<ShoppingCart> list =  shoppingCartService.showShoppingCart();

        return Result.success(list);

    }

ShoppingCartService接口代码

    /**
     * 查看购物车
     * @return
     */
    List<ShoppingCart> showShoppingCart();

ShoppingCartServiceImpl代码

    /**
     * 查看购物车
     * @return
     */
    public List<ShoppingCart> showShoppingCart() {
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = ShoppingCart.builder()
                .userId(userId)
                .build();
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        return list;
    }

 测试成功显示

清空购物车

 

 ShoppingCartController代码

    /**
     * 清空购物车
     * @return
     */
    @DeleteMapping("/clean")
    @ApiOperation("清空购物车")
    public Result clean(){

        shoppingCartService.cleanShoppingCart();

        return Result.success();
    }

ShoppingCartService接口代码

    /**
     * 清空购物车
     */
    void cleanShoppingCart();

  

ShoppingCartServiceImpl代码

    /**
     * 清空购物车
     */
    public void cleanShoppingCart() {

        //获取到当前的微信用户的id
        Long userId = BaseContext.getCurrentId();
        shoppingCartMapper.cleanShoppingCart(userId);
    }

ShoppingCartMapper接口代码

    /**
     * 根据用户id删除购物车数据
     */
    @Delete("delete from shopping_cart where user_id = #{userId}")
    void cleanShoppingCart(Long userId);

功能测试,成功

 

删除购物车中一个商品 

产品原型

接口设计

数据模型

 

 

  ShoppingCartController代码

    /**
     * 删除购物车中一个商品
     * @return
     */
    @PostMapping("/sub")
    @ApiOperation("删除购物车中一个商品")
    public Result sub(@RequestBody ShoppingCartDTO shoppingCartDTO){
        log.info("删除购物车中一个商品,商品:{}", shoppingCartDTO);
        shoppingCartService.subShoppingCart(shoppingCartDTO);

        return Result.success();
    }

ShoppingCartService接口代码

    /**
     * 删除购物车中一个商品
     * @param shoppingCartDTO
     */
    void subShoppingCart(ShoppingCartDTO shoppingCartDTO);

  

ShoppingCartServiceImpl代码

 /**
     * 删除购物车中一个商品
     * @param shoppingCartDTO
     */
    public void subShoppingCart(ShoppingCartDTO shoppingCartDTO) {
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);
        //设置查询条件,查询当前登录用户的购物车数据
        shoppingCart.setUserId(BaseContext.getCurrentId());

        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);

        if(list != null && list.size() > 0){
            shoppingCart = list.get(0);

            Integer number = shoppingCart.getNumber();
            if(number == 1){
                //当前商品在购物车中的份数为1,直接删除当前记录
                shoppingCartMapper.deleteById(shoppingCart.getId());
            }else {
                //当前商品在购物车中的份数不为1,修改份数即可
                shoppingCart.setNumber(shoppingCart.getNumber() - 1);
                shoppingCartMapper.updateNumberById(shoppingCart);
            }
        }
    }

ShoppingCartMapper接口代码

    /**
     * 根据id删除购物车数据
     * @param id
     */
    @Delete("delete from shopping_cart where id = #{id}")
    void deleteById(Long id);

功能测试,成功

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1962246.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【排序算法】Java实现三大非比较排序:计数排序、桶排序、基数排序

非比较排序概念 非比较排序是一种排序算法&#xff0c;它不通过比较元素之间的大小关系来进行排序&#xff0c;而是基于元素的特征或属性进行排序。这种方法在特定情况下可以比比较排序方法&#xff08;如快速排序、归并排序等&#xff09;更有效率&#xff0c;尤其是在处理大…

时间序列分析方法之 -- 长短期记忆网络(LSTM)原理及Python代码示例

目录 原理 适用情况 Python示例代码 结论 原理 长短期记忆网络&#xff08;LSTM&#xff0c;Long Short-Term Memory Networks&#xff09;是一种特殊的递归神经网络&#xff08;RNN&#xff09;&#xff0c;设计用于克服传统RNN在处理长序列数据时的梯度消失和梯度爆炸问…

如何在基于滤波框架的绝对定位系统中融合相对观测

文章目录 1 LIO、VIO propagation来代替IMU propagation2 TRO paper: Stochastic Cloning Kalman filter【有待填坑】 以无人驾驶定位系统为例&#xff0c;融合gnss&#xff0c;imu&#xff0c;轮速&#xff0c;camera LaneMatch(frame to map)&#xff0c;lidar scan match(fr…

Qgis 插件升级:3.28到3.34

1、下载 osgeo4w-setup 安装包 下载 获取 osgeo4w-setup.exe 的安装软件&#xff0c;每次下一步就可以了&#xff0c;安装位置可以自己调整 osgeo4w:https://download.osgeo.org/osgeo4w/osgeo4w-setup.exe 2、安装3.34 开发包 搜索qigs&#xff0c;将 desktop&#xff0c;…

开始使用OKR创建注重结果的文化

亚马逊对客户很痴迷。Facebook 行动迅速。成功企业的文化是传说中的东西&#xff0c;而且是正确的。正如管理顾问的名言&#xff1a;文化把战略当早餐吃。 无论行业或规模如何&#xff0c;文化的主要目标是激发企业获胜所需的行为。越来越多的成功要求企业关注结果而非任务&am…

Kafka的入门及简单使用

文章目录 前言一、Kafka 的基本架构&#xff1f;1. Producer&#xff08;生产者&#xff09;2. Broker&#xff08;代理/服务器&#xff09;3. Consumer&#xff08;消费者&#xff09;4. Consumer Group&#xff08;消费者组&#xff09;5. Topic&#xff08;主题&#xff09;…

docker前端部署

挂载&#xff0c;把自己的目录位置&#xff0c;挂载到容器内的HTML

万亿赛道!AI 大模型典型应用深度分析 2024

大模型由于其强大的自然语言与多模态信息处理能力&#xff0c;可以应对不同语义粒度下的任务,进行复杂的逻辑推理&#xff0c;还具有超强的迁移学习和少样本学习能力, 可以快速掌握新的任务, 实现对不同领域、不同数据模式的适配&#xff0c;这些特点使得大模型较容易的赋能其他…

吴恩达机器学习C1W2Lab05-使用Scikit-Learn进行线性回归

前言 有一个开源的、商业上可用的机器学习工具包&#xff0c;叫做scikit-learn。这个工具包包含了你将在本课程中使用的许多算法的实现。 目标 在本实验中&#xff0c;你将: 利用scikit-learn实现使用梯度下降的线性回归 工具 您将使用scikit-learn中的函数以及matplotli…

付费进群系统源码原版最新修复全开源版

付费进群&#xff0c;和平时所见到的别人拉你进群是不一样的&#xff0c;付费进群需要先缴费以后&#xff0c;才会看到群的二维码&#xff0c;扫码进群或者是长按二维码图片识别进群&#xff0c;付费进群这个功能广泛应用于拼多多的砍价群&#xff0c;活动的助力群&#xff0c;…

Chapter 21 深入理解JSON

欢迎大家订阅【Python从入门到精通】专栏&#xff0c;一起探索Python的无限可能&#xff01; 文章目录 前言一、JSON数据格式1. 什么是JSON&#xff1f;2. JSON数据的格式 二、JSON格式数据转化三、格式化JSON数据的在线工具 前言 在当今数据驱动的世界中&#xff0c;JSON&…

【大模型系列篇】Vanna-ai基于检索增强(RAG)的sql生成框架

简介 Vanna是基于检索增强(RAG)的sql生成框架 Vanna 使用一种称为 LLM&#xff08;大型语言模型&#xff09;的生成式人工智能。简而言之&#xff0c;这些模型是在大量数据&#xff08;包括一堆在线可用的 SQL 查询&#xff09;上进行训练的&#xff0c;并通过预测响应提示中最…

中间件安全:Nginx 解析漏洞测试.

中间件安全&#xff1a;Nginx 解析漏洞测试. Nginx 是一个高性能的 HTTP和 反向代理服务器&#xff0c;Nginx 解析漏洞是一个由于配置不当导致的安全问题&#xff0c;它不依赖于Nginx或PHP的特定版本&#xff0c;而是由于用户配置错误造成的。这个漏洞允许攻击者上传看似无害的…

通俗易懂,车载显示屏简单介绍!

2024年后&#xff0c;小汽车产量的年增长率预计将在1%至3%之间 2023年在COVID完全解封后&#xff0c;全球汽车销售数量提升至8千8百万台车。2024预估微幅增加到 9000万辆&#xff0c; 自2024起&#xff0c;年成长率预期将放缓至3%以下。全球汽车主要销售前三大市场 (比较2022年…

为什么阿里开发手册不建议使用Date类?

在日常编码中&#xff0c;基本上99%的项目都会有一个DateUtil工具类&#xff0c;而时间工具类里用的最多的就是java.util.Date。 大家都这么写&#xff0c;这还能有问题&#xff1f;&#xff1f; 当你的“默认常识”出现问题&#xff0c;这个打击&#xff0c;就是毁灭性的。 …

BUG解决(vue3+echart报错):Cannot read properties of undefined (reading ‘type‘)

这是 vue3echart5 遇到的报错&#xff1a;Cannot read properties of undefined (reading ‘type‘) 这个问题需要搞清楚两个关键方法&#xff1a; toRaw&#xff1a; 作用&#xff1a;将一个由reactive生成的响应式对象转为普通对象。 使用场景&#xff1a; 用于读取响应式…

idea2023 总报Low memory

idea2023 总报Low memory 问题背景问题处理 问题背景 在日常开发中&#xff0c;使用idea2023开发工具&#xff0c;开发过程中总会遇到idea提示Low memory的情况&#xff0c;并且每当提示出现的时候&#xff0c;整个idea页面便什么也不能操作了&#xff0c;如何处理这个情况呢&…

AI测试:人工智能模型的核心测试指标,分类判别、目标检测、图像分割、定量计算分别有哪些指标?

在前面的人工智能测试技术系列文章中&#xff0c;我们详细介绍了人工智能测试的技术方法和实践流程。在了解人工智能测试方法后&#xff0c;我们需要进一步学习和研究如何衡量这些方法的有效性&#xff0c;即人工智能模型测试指标的选择。测试指标的选择主要取决于模型的类型和…

借助大语言模型快速升级你的 Java 应用程序

大家都知道我爱小 Q。在我“转码”的征程中&#xff0c;它就像上帝之手&#xff0c;在我本该枯燥漫长的学习进程中拉满快进条。 不仅是我&#xff0c;最近 Amazon Q Developer 还帮助 Amazon 一个由 5 人组成的团队在短短两天内将 1,000 多个生产应用程序从 Java 8 升级到 Jav…

Spring Cloud 组件

1.eureka注册中心原理简述 1.服务注册: Eureka Client 会通过发送rest请求的方式向eureka服务端注册自身元数据:ip地址,端口,运行状况等信息,服务端会把注册信息存储在一个双层map中。 Eureka 的数据存储分了两层&#xff1a;数据存储层和缓存层。 Eureka Client 在拉取服务信息…