苍穹外卖(第七天)
缓存菜品
用户端访问比较大,数据库压力增大
通过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);
}