当前位置: 首页 > news >正文

苍穹外卖(第七天)

缓存菜品

用户端访问比较大,数据库压力增大
通过redis来缓存菜品数据,减少数据库查询操作

先判断是否缓存了相关数据

缓存逻辑分析:
每个分类下的菜品保存一份缓存数据
数据库中菜品数据有变更要更新

缓存套餐

spring cache基于注解的缓存功能
提供了一层抽象,底层可以切换不同的缓存实现:
EHCache
Caffeine
Redis

常用注解:
@EnableCaching:开启缓存注解功能,通常加载启动类上
@Cacheable:执行方法前查询缓存中是否有数据,如果有数据,直接返回,没有则调用方法,并将方法返回值放到缓存
@CachePut:将方法的返回值放到缓存中
@CacheEvict:将一条或多条数据从缓存中删除

spring正则语言:
#result(返回值对象)
#p0(第一个参数)

实现思路:
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注解

    @GetMapping("/list")@ApiOperation("获取套餐")@Cacheable(cacheNames="setmealCache",key="#categoryId")public Result<List<Setmeal>> getByCategoryId(Long categoryId){Setmeal setmeal = new Setmeal();setmeal.setCategoryId(categoryId);setmeal.setStatus(StatusConstant.ENABLE);List<Setmeal> list=setmealService.getByCategoryId(setmeal);return Result.success(list);}

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

package com.sky.controller.admin;import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.SetmealService;
import com.sky.vo.SetmealVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;import java.util.List;@RestController
@RequestMapping("/admin/setmeal")
@Api(tags = "套餐管理")
@Slf4j
public class SetmealController {@Autowiredprivate SetmealService setmealService;@GetMapping("/page")@ApiOperation("套餐分页查询")public Result<PageResult> page(SetmealPageQueryDTO setmealPageQueryDTO){//分页查询接收分页dto,返回分页数据log.info("套餐分页查询,{}",setmealPageQueryDTO);PageResult pageResult=setmealService.pageQuery(setmealPageQueryDTO);return Result.success(pageResult);}@PostMapping@ApiOperation("新增套餐")@CacheEvict(cacheNames = "setmealCache",key = "#setmealDTO.categoryId")public Result insert(@RequestBody SetmealDTO setmealDTO){setmealService.insert(setmealDTO);return Result.success();}@DeleteMapping@ApiOperation("删除套餐")@CacheEvict(cacheNames = "setmealCache",allEntries = true)public Result deleteBatch(@RequestParam List<Long> ids){setmealService.deleteBatch(ids);return Result.success();}@GetMapping("/{id}")@ApiOperation("套餐回显")public Result<SetmealVO> getById(@PathVariable Long id){SetmealVO setmealVO=setmealService.getById(id);return Result.success(setmealVO);}@PutMapping@ApiOperation("修改套餐")@CacheEvict(cacheNames = "setmealCache",allEntries = true)public Result update(@RequestBody SetmealDTO setmealDTO){setmealService.update(setmealDTO);return Result.success();}@PostMapping("/status/{status}")@ApiOperation("修改菜品状态")@CacheEvict(cacheNames="setmealCache",allEntries=true)public Result startOrStop(@PathVariable Integer status,Long id){setmealService.changeStatus(status,id);return Result.success();}}

添加购物车

 @Autowiredprivate ShoppingCartService shoppingCartService;@PostMapping("/add")@ApiOperation("添加商品")public Result add(@RequestBody ShoppingCartDTO shoppingCartDTO){shoppingCartService.addShop(shoppingCartDTO);return Result.success();}@GetMapping("/list")@ApiOperation("获取购物车数据")public Result<List<ShoppingCart>> list(){List<ShoppingCart> list=shoppingCartService.getList();return Result.success(list);}@DeleteMapping("/clean")@ApiOperation("清空购物车")public Result clean(){shoppingCartService.clean();return Result.success();}@PostMapping("/sub")@ApiOperation("删除一个菜品")public Result sub(@RequestBody ShoppingCartDTO shoppingCartDTO){shoppingCartService.sub(shoppingCartDTO);return Result.success();}
 @Autowiredprivate ShoppingCartMapper shoppingCartMapper;@Autowiredprivate DishMapper dishMapper;@Autowiredprivate SetmealMapper setmealMapper;@Overridepublic void addShop(ShoppingCartDTO shoppingCartDTO) {//判断是否存在该商品ShoppingCart shoppingCart=new ShoppingCart();Long userId=BaseContext.getCurrentId();shoppingCart.setUserId(userId);BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);List<ShoppingCart> list=shoppingCartMapper.list(shoppingCart);//存在直接更新+1if(list!=null&&list.size()>0){shoppingCart=list.get(0);shoppingCart.setNumber(shoppingCart.getNumber()+1);shoppingCartMapper.update(shoppingCart);return ;}Long dishId=shoppingCartDTO.getDishId();Long setmealId=shoppingCartDTO.getSetmealId();if(dishId!=null){Dish dish=dishMapper.getById(dishId);//添加菜品数据shoppingCart.setName(dish.getName());shoppingCart.setAmount(dish.getPrice());shoppingCart.setImage(dish.getImage());}else{Setmeal setmeal=setmealMapper.getById(setmealId);//添加套餐数据shoppingCart.setName(setmeal.getName());shoppingCart.setAmount(setmeal.getPrice());shoppingCart.setImage(setmeal.getImage());}shoppingCart.setNumber(1);shoppingCart.setCreateTime(LocalDateTime.now());//添加套餐数据shoppingCartMapper.insert(shoppingCart);}@Overridepublic List<ShoppingCart> getList() {ShoppingCart shoppingCart=new ShoppingCart();shoppingCart.setUserId(BaseContext.getCurrentId());return shoppingCartMapper.list(shoppingCart);}@Overridepublic void clean() {shoppingCartMapper.deleteAll(BaseContext.getCurrentId());}@Overridepublic void sub(ShoppingCartDTO shoppingCartDTO) {//拿到数据ShoppingCart shoppingCart = new ShoppingCart();BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);shoppingCart.setUserId(BaseContext.getCurrentId());List<ShoppingCart> list=shoppingCartMapper.list(shoppingCart);shoppingCart=list.get(0);//为1直接删除if(shoppingCart.getNumber()==1){shoppingCartMapper.delete(shoppingCart.getId());return;}//不为1减少shoppingCart.setNumber(shoppingCart.getNumber()-1);shoppingCartMapper.update(shoppingCart);}
<?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"><insert id="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})</insert><select id="list" resultType="com.sky.entity.ShoppingCart">select id, name, image, user_id, dish_id, setmeal_id, dish_flavor, number, amount, create_timefrom shopping_cart<where><if test="userId!=null">and user_id=#{userId}</if><if test="dishId!=null">and dish_id=#{dishId}</if><if test="setmealId!=null">and setmeal_id=#{setmealId}</if><if test="dishFlavor!=null">and dish_flavor=#{dishFlavor}</if></where></select>
</mapper>
@Mapper
public interface ShoppingCartMapper {List<ShoppingCart> list(ShoppingCart shoppingCart);@Update("update shopping_cart set number=#{number} where id=#{id}")void update(ShoppingCart shoppingCart);void insert(ShoppingCart shoppingCart);@Delete("delete from shopping_cart where user_id=#{userId}")void deleteAll(Long userId);@Delete("delete from shopping_cart where id=#{id}")void delete(Long id);
}
http://www.dtcms.com/a/601449.html

相关文章:

  • 新乡网站建设制作报价方案网站如何布局
  • 安全狗 网站打不开成都网络营销搜索推广
  • 预测汽车燃油效率——线性回归
  • 【自然语言处理】基于深度学习基的句子边界检测算法
  • 链接脚本(Linker Scripts)
  • 素材网站整站下载WordPress做图床
  • 企业网站相关案例网站建设域名怎么用
  • 太原专业做网站wordpress主体开发
  • 零基础新手小白快速了解掌握服务集群与自动化运维(十八)Ansible自动化模块--安装与入门
  • 【C++11】Lambda表达式+新的类功能
  • C语言编译工具 | 探讨常用C语言编译工具的选择与使用
  • SCT2A26——5.5V-100V Vin,4A峰值电流限制,高效率非同步降压DCDC转换器,兼容替代LM5012
  • 手机网站搜索框代码网上做网站怎么防止被骗
  • 滑动窗口(同向双指针)
  • C语言嵌入式编程实战指南(四):进阶技术和未来展望
  • Mac上的C语言编译软件推荐与使用指南 | 如何选择适合你需求的C语言编译器
  • 做建站较好的网站wordpress edit.php
  • 【大语言模型】-- Function Calling函数调用
  • STM32项目分享:花房环境监测系统
  • 第1章 认识Qt
  • JDK 25 重大兼容性 Bug
  • MyBatis多表联查返回List仅一条数据?主键冲突BUG排查与解决
  • c 做网站方便吗手机企业wap网站
  • el-table有固定列时样式bug
  • Vue项目中 安装及使用Sass(scss)
  • 珠海本地网站设计公司什么网站可以发布信息
  • UEFI+GPT平台一键安装Windows方法
  • GPT‑5 全面解析与开发者接入指南
  • 站优云seo优化页面模板这样选
  • dism++功能实操备份与还原