苍穹外卖项目Day07
1、缓存菜品
1.1、问题说明
用户端小程序展示的菜品数据都是通过查询数据库获得,如果用户端访问量比较大,数据库访问压力随之增大
1.2、实现思路
通过Redis来缓存菜品的数据,减少数据库查询操作
缓存逻辑分析:
-
每个分类下的菜品保存一份缓存数据
-
数据库中菜品数据有变更时清理缓存数据
1.3、代码开发
user\DishController
@Autowired
private RedisTemplate redisTemplate;@GetMapping("/list")@ApiOperation("根据分类id查询菜品")public Result<List<DishVO>> list(Long categoryId) {//构造redis中的key,规则:dish_分类idString key = "dish_" +categoryId;//查询redis中是否存在菜品数据List<DishVO> list = (List<DishVO>) redisTemplate.opsForValue().get(key);if (list != null && list.size()>0){//如果存在,直接返回,无须查询数据库return Result.success(list);}Dish dish = new Dish();dish.setCategoryId(categoryId);dish.setStatus(StatusConstant.ENABLE);//查询起售中的菜品//如果不存在,查询数据库,将查询到的数据放入redis中list = dishService.listWithFlavor(dish);redisTemplate.opsForValue().set(key,list);return Result.success(list);}
admin\DishController
@Autowired
private RedisTemplate redisTemplate;/*** 清理缓存数据* @param pattern*/private void CleanCache(String pattern){Set keys = redisTemplate.keys(pattern);redisTemplate.delete(keys);}/*** 修改菜品* @param dishDTO* @return*/@PutMapping@ApiOperation("修改菜品")public Result update(@RequestBody DishDTO dishDTO){log.info("修改菜品:{}",dishDTO);dishService.updateWithFlavor(dishDTO);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_开头的keyCleanCache("dish_*");return Result.success();}/***菜品批量删除* @param ids* @return*/@DeleteMapping@ApiOperation("菜品批量删除")public Result delete(@RequestParam List<Long> ids){log.info("菜品批量删除:{}",ids);dishService.deleteBatch(ids);//将所有的菜品缓存数据清理掉,所有以dish_开头的keyCleanCache("dish_*");return Result.success();}/*** 新增菜品* @param dishDTO* @return*/@PostMapping@ApiOperation("新增菜品")public Result save(@RequestBody DishDTO dishDTO){log.info("新增菜品:{}",dishDTO);dishService.saveWithFalvor(dishDTO);//清理缓存数据String key = "dish_" + dishDTO.getCategoryId();CleanCache(key);return Result.success();}
1.4、功能测试
在管理端更改的数据会同步到用户端,利用redis的缓存机制,当管理端修改数据时,用户端会删除缓存重新获取,保持与管理端的数据信息一致
2、缓存套餐
2.1、Spring Cache
SpringCache是一个框架,实现了基于注解的缓存功能,只需要简单地加一个注解,就能实现缓存功能
Spring Cache提供了一层抽象,底层可以切换不同的缓存实现,例如:
- EHCache
- Caffeine
- 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>
常用注解:
注解 | 说明 |
---|---|
@EnableCaching | 开启缓存注解功能,通常加在启动类上 |
@Cacheable | 在方法执行前先查询缓存中是否有数据,如果有数据,则直接返回缓存数据;如果没有缓存数据,调用方法并将方法返回值放到缓存中 |
@CachePut | 将方法的返回值放到缓存中 |
@CacheEvict | 将一条或多条数据从缓存中删除 |
2.2、实现思路
具体实现思路如下:
- 导入Spring Cache和Redis相关maven坐标
- 在启动类上加入@EnableCaching注解,开启缓存注解功能
- 在用户端接口SetmealController的list方法上加入@Cacheable注解
- 在管理端接口SetmealController的save、delete、update、startOrStop等方法上加入CacheEvict注解
2.3、代码开发
1、在启动类上加入注解@EnableCaching
user\SetmealController
@Cacheable(cacheNames = "setmealCache",key = "#categoryId") //key:setmealCache::100
public Result<List<Setmeal>> list(Long categoryId) {}
admin\SetmealController
@CacheEvict(cacheNames = "setmealCache",allEntries = true)
public Result save(@RequestBody SetmealDTO setmealDTO){}
3、添加购物车
3.1、需求分析和设计
接口设计:
- 请求方式:POST
- 请求路径:/user/shopping/add
- 请求参数:套餐id,菜品id,口味
- 返回结果:code、data、msg
数据库设计:
- 作用:暂时存放所选商品的地方
- 选的什么商品
- 每个商品都买了几个
- 不同用户的购物车需要区分开
3.2、代码开发
ShoppingCartController
@RestController
@RequestMapping("/user/shoppingCart")
@Slf4j
@Api(tags = "C端购物车相关接口")
public class ShoppingCartController {@Autowiredprivate 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 {@Autowiredprivate ShoppingCartMapper shoppingCartMapper;@Autowiredprivate DishMapper dishMapper;@Autowiredprivate SetmealMapper setmealMapper;/*** 添加购物车* @param shoppingCartDTO*/@Overridepublic 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 sky_take_out.shopping_cart set number = #{number} where id =#{id}")void updateNumberById(ShoppingCart shoppingCart);/*** 插入购物车数据* @param shoppingCart*/@Insert("insert into sky_take_out.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
<!DOCTYPE mapperPUBLIC "-//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 sky_take_out.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>
4、查看购物车
4.1、需求分析和设计
接口设计:
4.2、代码开发
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*/
@Override
public List<ShoppingCart> showShoppingCart() {//获取到当前微信用户的idLong userId = BaseContext.getCurrentId();ShoppingCart shoppingCart = ShoppingCart.builder().userId(userId).build();List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);return list;
}
4.3、功能测试
5、清空购物车
5.1、需求分析和设计
5.2、代码开发
ShoppingCartController
/*** 清空购物车* @return*/
@DeleteMapping("/clean")
@ApiOperation("清空购物车")
public Result clean(){shoppingCartService.cleanShoppingCart();return Result.success();
}
ShoppingCartService
/*** 清空购物车*/
void cleanShoppingCart();
ShoppingCartServiceImpl
/*** 清空购物车*/
@Override
public void cleanShoppingCart() {//获取到当前微信用户的idLong userId = BaseContext.getCurrentId();shoppingCartMapper.deleteByUserId(userId);
}
ShoppingMapper
@Delete("delete from sky_take_out.shopping_cart where user_id = #{userId}")
void deleteByUserId(Long userId);
ngCart();return Result.success();
}
ShoppingCartService
/*** 清空购物车*/
void cleanShoppingCart();
ShoppingCartServiceImpl
/*** 清空购物车*/
@Override
public void cleanShoppingCart() {//获取到当前微信用户的idLong userId = BaseContext.getCurrentId();shoppingCartMapper.deleteByUserId(userId);
}
ShoppingMapper
@Delete("delete from sky_take_out.shopping_cart where user_id = #{userId}")
void deleteByUserId(Long userId);
购物车其他功能代码
1. 删除购物车中一个商品
1.1 产品原型
1.2 接口设计
1.3 数据模型
shopping_cart表:
1.4 代码开发
1.4.1 ShoppingCartController
/*** 删除购物车中一个商品* @param shoppingCartDTO* @return
*/
@PostMapping("/sub")
@ApiOperation("删除购物车中一个商品")
public Result sub(@RequestBody ShoppingCartDTO shoppingCartDTO){log.info("删除购物车中一个商品,商品:{}", shoppingCartDTO);shoppingCartService.subShoppingCart(shoppingCartDTO);return Result.success();
}
1.4.2 ShoppingCartService
/*** 删除购物车中一个商品* @param shoppingCartDTO
*/
void subShoppingCart(ShoppingCartDTO shoppingCartDTO);
1.4.3 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);}}
}
1.4.4 ShoppingCartMapper
/*** 根据id删除购物车数据* @param id
*/
@Delete("delete from shopping_cart where id = #{id}")
void deleteById(Long id);