前言
代碼鏈接:
Echo0701/take-out? (github.com)
1 緩存菜品
1.1 問題說明
【注】很多時候系統性能的瓶頸就在于數據庫這端
1.2 實現思路
通過 Redis 來緩存數據,減少數據庫查詢操作
【注】Redis 基于內存來保存數據的,訪問 Redis 數據本質上是對內存的操作,而查詢數據庫本質上是對磁盤IO的操作
緩存邏輯分析:?
1.3 代碼開發
1.3.1 緩存菜品數據
DishController.java
@RestController("userDishController")
@RequestMapping("/user/dish")
@Slf4j
@Api(tags = "C端-菜品瀏覽接口")
public class DishController {@Autowiredprivate DishService dishService;@Autowiredprivate RedisTemplate redisTemplate;/*** 根據分類id查詢菜品** @param categoryId* @return*/@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);}}
【注】如果出現異常:java.lang.reflect.InvocationTargetException,可能原因:
?① 未進行注入,檢查 @Autowired
?② 未啟動 Redis 服務器:打開?redis 的安裝目錄在地址欄輸入cmd,輸入
redis-server.exe redis.windows.conf
1.3.2 清理緩存數據
修改管理端接口 DishController 相關的方法,加入清理緩存的邏輯,需要改造的方法有:
- 新增菜品
- 批量刪除菜品
- 修改菜品
- 起售停售
2 緩存套餐
2.1 Spring Cache
2.1.1 簡介
Spring Cache 是一個框架,實現了基于注解的緩存功能,只需要簡單的加一個注釋,就能實現緩存功能。它提供了一層抽象,底層可以切換不同的緩存實現,例如:
- EHCache
- Caffeine
- Redis(本項目實現)
maven 坐標:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId><version>2.7.3</version></dependency>
2.1.2 常用注解
2.2 實現思路
3 添加購物車
3.1 需求分析和設計
產品原型
接口設計
- 請求方式:POST
- 請求路徑:/user/shoppingCart/add
- 請求參數:套餐id、菜品id、口味
- 返回結果:code、data、msg
數據庫設計?
- 購物車:暫時存放所選商品的地方
- 選的什么商品
- 每個商品買了幾個
- 不同用戶的購物車需要區分開
【注】冗余字段(比較穩定)的設計可以幫助我們提高查詢速度?,但冗余字段不可大量設計
3.2 代碼開發
ShoppingCartController.java
@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();}/*** 查看購物車* @return*/@GetMapping("/list")@ApiOperation("查看購物車")public Result<List<ShoppingCart>> list() {List<ShoppingCart> list = shoppingCartService.showShoppingCart();return Result.success(list);}/*** 清空購物車* @return*/@DeleteMapping("/clean")@ApiOperation("清空購物車")public Result clean() {shoppingCartService.cleanShoppingCart();return Result.success();}/*** 減少購物車商品* @param shoppingCartDTO* @return*/@PostMapping("/sub")@ApiOperation("減少購物車商品數量")public Result sub(@RequestBody ShoppingCartDTO shoppingCartDTO) {log.info("減少購物車商品數量,商品信息為:{}", shoppingCartDTO);shoppingCartService.subShoppingCart(shoppingCartDTO);return Result.success();}
}
?
ShoppingCartServiceImpl.java
/*** 添加購物車* @param shoppingCartDTO*/public void addShoppingCart(ShoppingCartDTO shoppingCartDTO) {// 判斷當前添加的商品是否已經在購物車中存在了//select * from shopping_cart where user_id = ? and setmeal_id = xx//select * from shopping_cart where user_id = ? and dish_id = xx and dish_flavorShoppingCart shopingCart = new ShoppingCart();BeanUtils.copyProperties(shoppingCartDTO, shopingCart);Long userId = BaseContext.getCurrentId();shopingCart.setUserId(userId);List<ShoppingCart> list = shoppingCartMapper.list(shopingCart);// 若存在,只需要進行update方法更新商品數量,if(list != null && list.size() > 0) {//查到了,把這條購物車數據獲取到,把 num + 1//由于user_id是唯一的,再加上上面的信息限制,所以查詢的結果只可能有兩種:1、查不到;2、查出來唯一的一條數據ShoppingCart cart = list.get(0);cart.setNumber(cart.getNumber() + 1); //加 1 操作以后,執行update語句:update shopping_cart set number = ? where id = ?shoppingCartMapper.updateNumberById(cart);} else{// 如果不存在才需要在購物車表里面插入一條新的數據//購物車對象仍然可以使用上面的shoppingcart,但是商品的名稱、價格、圖片仍然需要查詢,如果是套餐到套餐表里面去查詢,如果是菜品到菜品表里面去查詢//判斷本次添加到購物車的是菜品還是套餐,可以通過判斷它們的id 是否為空來進行判斷Long dishId = shoppingCartDTO.getDishId();if(dishId != null){//本次添加到購物車的是菜品Dish dish = dishMapper.getById(dishId);shopingCart.setName(dish.getName());shopingCart.setImage(dish.getImage());shopingCart.setAmount(dish.getPrice());} else {//本次添加到購物車的是套餐Long setmealId = shoppingCartDTO.getSetmealId();Setmeal setmeal = setmealMapper.getById(setmealId);shopingCart.setName(setmeal.getName());shopingCart.setImage(setmeal.getImage());shopingCart.setAmount(setmeal.getPrice());}shopingCart.setNumber(1);shopingCart.setCreateTime(LocalDateTime.now());shoppingCartMapper.insert(shopingCart);}}
ShoppingCartMapper.xml??
<insert id="insertBatch" parameterType="list">insert into shopping_cart (name, image, user_id, dish_id, setmeal_id, dish_flavor, number, amount, create_time)values<foreach collection="shoppingCartList" item="sc" separator=",">(#{sc.name},#{sc.image},#{sc.userId},#{sc.dishId},#{sc.setmealId},#{sc.dishFlavor},#{sc.number},#{sc.amount},#{sc.createTime})</foreach></insert>
4 查看購物車
4.1 需求分析和設計
產品原型
接口設計?
4.2 代碼開發
ShoppingCartServiceImpl.java
/*** 查看購物車* @return*/public List<ShoppingCart> showShoppingCart() {//獲取當前微信用戶的idLong userId = BaseContext.getCurrentId();ShoppingCart shoppingCart = ShoppingCart.builder().userId(userId).build();List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);return list;}
ShoppingCartMapper.xml?
<select id = "list" resultType="com.sky.entity.ShoppingCart">select * from shopping_cart<where>
<!-- test里面寫的屬性名,然后是表字段名 = #{屬性名}--><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>
5 清空購物車
5.1 需求分析和設計
接口設計
5.2 代碼開發
ShoppingCartServiceImpl.java
/*** 清空購物車*/public void cleanShoppingCart() {//獲取當前微信用戶的idLong userId = BaseContext.getCurrentId();shoppingCartMapper.deleteByUserId(userId);}
?ShoppingCartMapper.java
@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 shopingCart*/@Insert("insert into shopping_cart(name, user_id, dish_id, setmeal_id, dish_flavor, number, amount, image, create_time)" +"values (#{name}, #{userId}, #{dishId}, #{setmealId}, #{dishFlavor}, #{number}, #{amount}, #{image}, #{createTime})")void insert(ShoppingCart shopingCart);/*** 根據用戶 id 清空購物車* @param userId*/@Delete("delete from shopping_cart where user_id = #{userId}")void deleteByUserId(Long userId);/*** 根據商品 id 刪除購物車數據* @param id*/@Delete("delete from shopping_cart where id = #{id}")void deleteById(Long id);/*** 批量插入購物車*/void insertBatch(List<ShoppingCart> shoppingCartList);
}
?