首页 > 其他分享 >缓存套餐数据

缓存套餐数据

时间:2023-04-07 19:57:09浏览次数:35  
标签:queryWrapper 缓存 return com 套餐 import 数据 setmeal

SetmealController的list方法,此方法会根据前端提交的查询条件进行数据库查询操作。在高并发的情况下,频繁查询数据库会导致系统性能下降,服务端响应时间增长。

对此方法进行缓存优化,提高系统的性能:

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

2、在application.yml中配置缓存数据的过期时间

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

4、在SetmealController的list方法上加入@Cacheable注解

5、在SetmealController的save和update方法上加入CacheEvict注解

package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.SetmealDto;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.Setmeal;
import com.itheima.entity.SetmealDish;
import com.itheima.service.CategoryService;
import com.itheima.service.DishService;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 套餐管理
 */
@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {

    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishService dishService;

    /**
     * 新增套餐
     * @param setmealDto
     * 删除缓存里面setmealcache下的数据
     * @return
     */
    @PostMapping
    @CacheEvict(value = "setmealCache", allEntries = true)
    public R<String> add(@RequestBody SetmealDto setmealDto){
        setmealService.saveWithDish(setmealDto);
        return R.success("新增套餐成功");

    }

    /**
     * 套餐分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name){
        //创建分页构造器
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);

        //创建条件构造器
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件,根据name进行like模糊查询
        queryWrapper.like(name!=null, Setmeal::getName, name);
        //添加排序条件,根据更新时间降序排列
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        setmealService.page(pageInfo, queryWrapper);

        Page<SetmealDto> dtoPage = new Page(page, pageSize);
        //对象拷贝,因为pageInfo中的records是Setmeal类型,而dtoPage中的records是SetmealDto类型
        BeanUtils.copyProperties(pageInfo, dtoPage, "records");
        List<Setmeal> records = pageInfo.getRecords();
        //通过category_id查询categoryName
        List<SetmealDto> list = records.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            //对象拷贝
            BeanUtils.copyProperties(item, setmealDto);
            //根据categoryId查询分类对象category
            Category category = categoryService.getById(item.getCategoryId());
            if(category!=null){
                setmealDto.setCategoryName(category.getName());
            }
            return setmealDto;
        }).collect(Collectors.toList());

        dtoPage.setRecords(list);
        return R.success(dtoPage);

    }


    /**
     * 删除套餐:删除一个或者批量删除
     * 清理setmealCache套餐下的所有缓存数据
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "setmealCache", allEntries = true)
    public R<String> delete(@RequestParam List<Long> ids){
//        log.info("ids:{}", ids);
        setmealService.removeWithDish(ids);
        return R.success("套餐数据删除成功");
    }

    /**
     * 套餐的启售、停售、批量修改售卖状态
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> statusChange(@PathVariable int status, @RequestParam List<Long>ids){

        List<Setmeal> setmeals = setmealService.listByIds(ids);
        //若status=1套餐要起售,则先查询该套餐包含的所有菜品的状态是否都为起售
        if(status==1){
            LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
            for(Setmeal setmeal : setmeals){
                //查询套餐中包含的菜品setmealDish
                queryWrapper.eq(SetmealDish::getSetmealId, setmeal.getId());
                List<SetmealDish> setmealDishes = setmealDishService.list(queryWrapper);
                //通过setmealDish中的dishId查询该菜品的status=0停售,status=1启售
                for(SetmealDish setmealDish : setmealDishes){
                    Dish dish = dishService.getById(setmealDish.getDishId());
                    //dish.status=0表示该菜品处于停售,因此包含该菜品的套餐setmeal无法更改售卖状态
                    if(dish.getStatus()==0){
                        return R.error("套餐状态修改失败,该套餐中存在餐品为停售状态");
                    }
                }
            }
        }

        for(Setmeal setmeal : setmeals){
            setmeal.setStatus(status);
        }

        setmealService.updateBatchById(setmeals);
        return R.success("状体修改成功");
    }

    /**
     * 根据id查询套餐信息和包含的菜品信息
     * 修改时回显数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<SetmealDto> get(@PathVariable Long id){
        SetmealDto setmealDto = setmealService.getByIdWithDish(id);
        return R.success(setmealDto);
    }

    /**
     *根据条件查询套餐数据
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "setmealCache", key = "#setmeal.categoryId + '_' + #setmeal.status")
    public R<List<Setmeal>> list(Setmeal setmeal){
        Long categoryId = setmeal.getCategoryId();
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(categoryId!=null, Setmeal::getCategoryId, categoryId);
        queryWrapper.eq(setmeal.getStatus()!=null, Setmeal::getStatus, setmeal.getStatus());
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        List<Setmeal> setmeals = setmealService.list(queryWrapper);
        return R.success(setmeals);
    }

    /**
     * 更新套餐表setmeal和对应的关联菜品信息setmeal_dish
     * @param setmealDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody SetmealDto setmealDto){

         setmealService.updateWithSetmealDish(setmealDto);
         return R.success("套餐更新成功");
    }



}

 

标签:queryWrapper,缓存,return,com,套餐,import,数据,setmeal
From: https://www.cnblogs.com/fxzm/p/17297183.html

相关文章

  • PHP代码实现网页缓存
    PHP程序在抵抗大流量访问的时候动态网站往往都是难以招架,所以要引入缓存机制,一般情况下有两种类型缓存:一、文件缓存二、数据查询结果缓存,使用内存来实现高速缓存本例主要使用文件缓存,主要原理使用缓存函数来存储网页显示结果,如果在规定时间里再次调用则可以加载缓存文件。类代码://......
  • 电商API原数据接口的应用场景
    电商API的作用主要有以下几点:1.方便第三方开发商和合作伙伴开发扩展应用,提升电商平台的业务价值。2.提高电商平台的运营效率和管理水平,缩短数据处理和交互的时间。3.对外提供规范统一的数据接口,降低了系统间的耦合度,保证了平台数据的安全性和稳定性。4.为电商平台的数据分析和......
  • 根据数据量来判断算法的复杂度
    根据数据量来判断算法的复杂度通过运行时间判断数据量1000ms即1s,大概可以运行10的7次方数量级的运算左边的复杂度在1s内能处理的数据量大小......
  • mysqldump 命令导出数据,解决中文乱码问题
      https://www.cnblogs.com/LoveBB/p/16941639.html mysqldump-uroot-ppassword--add-drop-table--default-character-set=utf8--hex-blobdbname--result-file=F:\backup.sql......
  • 同步合约数据到数据库经典案例1
    之前在《数字藏品发行平台的架构》里讲过,有一种架构希望以区块链的数据为核心。这样就需要将合约保存在区块链上的数据同步到数据库里,方便后续中间件接口的开发。本次我们以同步ConfirmSale事件日志为例,介绍数据同步程序开发的相关知识点。一、先上全部代码```javascriptconst{......
  • vue3学习第二课:组件和父组件的传递数据给子组件方式props
    1,在conponents目录中新建header.vue<template><div><h1>这是头部组件</h1></div></template>2,在App.vue中添加<template><div><Header></Header><Main></Main><Foote......
  • 查询mysql的数据库容量
    查看所有数据库容量大小SELECT table_schemaAS'数据库', sum(table_rows)AS'记录数', sum( TRUNCATE(data_length/1024/1024/1024,2))AS'数据容量(G)', sum( TRUNCATE(index_length/1024/1024/1024,2))AS'索引容量(G)'FRO......
  • Python数据分析库介绍及引入惯例
    文章和代码等已经归档至【Github仓库:https://github.com/timerring/dive-into-AI】或者公众号【AIShareLab】回复python数据分析也可获取。python的缺点Python有一个叫做全局解释器锁(GlobalInterpreterLock,GIL)的组件,这是一种防止解释器同时执行多条Python字节码指令的机制。这......
  • 记一次达梦数据库虚拟表SQL优化记录分享
    前言:遇到问题不要怕,先看一看。语句看懂了,创建个索引,优化个处理方式,30S变0.3秒,速度提升90倍。 背景:达梦数据库、督办定制功能的一个查询列表慢(虚拟表)。语句:selectidasdbrw,hzrwnr,createdate,BB,whbh01,whbh02,whbh03,zkh,ykh,sfyrq,qtkckry,(selectcount(wfrb.requestid)from......
  • DolphinDB +Python Airflow 高效实现数据清洗
    DolphinDB作为一款高性能时序数据库,其在实际生产环境中常有数据的清洗、装换以及加载等需求,而对于该如何结构化管理好ETL作业,Airflow提供了一种很好的思路。本篇教程为生产环境中ETL实践需求提供了一个解决方案,将PythonAirflow引入到DolphinDB的高可用集群中,通过使用Ai......