蒼穹外賣項目筆記(8)— 緩存商品、購物車功能

前言

代碼鏈接:

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);
}

?

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/210277.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/210277.shtml
英文地址,請注明出處:http://en.pswp.cn/news/210277.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

LeetCode208.實現Trie(前綴樹)

我一開始想題目叫前綴樹&#xff0c;是要用樹嗎&#xff1f;但是不知道用樹怎么寫&#xff0c;然后我就花了10多分鐘&#xff0c;用了HashMap解了。map的key是word&#xff0c;value是一個放了word的所有前綴的set&#xff0c;這樣search方法就非常簡單了&#xff0c;只要看has…

Leetcode—2048.下一個更大的數值平衡數【中等】

2023每日刷題&#xff08;五十四&#xff09; Leetcode—2048.下一個更大的數值平衡數 實現代碼 class Solution { public:int nextBeautifulNumber(int n) {for(int x n 1; ; x) {vector<int> cnt(10, 0);for(int y x; y > 0; y / 10) {cnt[y%10];}bool ok tru…

C++ Div3、Sqrt 函數高性能實現(帶匯編指令集)

均采用魔法數字&#xff08;Magic Number&#xff09;實現&#xff0c;一個是經典求平方根函數所使用的魔法數字&#xff1a;0x5f375a86、0x5f3759df。 float Sqrt(float x) noexcept { /* 0x5f3759df */float xhalf 0.5f * x;int32_t i *(int32_t*)&x;i 0x5f375a86 - …

TP5上傳圖片壓縮尺寸

圖片上傳&#xff0c;最簡單的就是&#xff0c; 方法一&#xff1a; 修改上傳限制&#xff0c;不讓上傳大于多少多少的圖片 改一下size即可&#xff0c;默認單位是B換算成M還需要除以兩次1024 方法二&#xff1a; 對上傳的圖片進行縮放&#xff0c;此辦法網上找了不少的代碼…

如何在 Azure Cosmos DB 中使用緩存

Cosmos DB 是微軟在 Azure 云中發布的新 NoSQL 數據庫。與關系數據庫不同&#xff0c;Cosmos DB 是一種托管數據庫服務&#xff0c;因此具有可擴展性&#xff0c;因此在高事務性 .NET 和 .NET Core 應用程序中很受歡迎。 但是&#xff0c;使用 Cosmos DB 時&#xff0c;您需要…

pytorch 鉤子函數hook 詳解及實戰

文章目錄 1. 介紹1.1 pytorch hook 函數種類1.2 pytorch hook 種類1.3 hook的執行順序2. torch.Tensor.register_hook()2.1 功能2.2 語法2.3 案例3. nn.Module.register_forward_pre_hook3.1 功能3.2 語法3.3 案例4. nn

連通分量提取

圖像形態學操作中的提取連通分量是一種用于分離圖像中相互連接的像素區域的技術。這些像素區域通常代表著圖像中的不同物體、目標或者區域。連通分量提取通常用于圖像分割、對象識別、特征提取等領域。 原理&#xff1a; ??連通分量提取基于圖像中像素的連接性。在這個過程中…

ECharts標題字體大小自適應變化

我們在做自適應Echarts的時候,字體大小在配置項里是如下配置的, title 標題組件,包含主標題和副標題。 以下是常用的對標題的設置: title:{//設置圖表的標題text:"主標題",link:"baidu.com", //設置標題超鏈接target:"self",

HCIP —— BGP 基礎 (下)

BGP 的狀態機 --- 建立對等體之間的TCP會話&#xff1a;指定建立對等體的對象 六種狀態機 Idle狀態 Idle 等待狀態&#xff08;相當于OSPF的down狀態&#xff09;--- 采用TCP單播建鄰 Idle 狀態下&#xff0c;啟動BGP協議后必須指定建立對等體的目標之后&#xff0c;才能進入…

yaml工作常用語法總結

文章目錄 yaml中的| 符號 和 > 符號yaml中的 - 符號工作中常遇到的問題- 命令行中有冒號加空格&#xff0c;導致yaml解析報錯 yaml中的| 符號 和 > 符號 在 YAML 中&#xff0c;| 符號表示標量塊&#xff08;Scalar Block&#xff09;的開始。它用于表示長文本塊或保持多…

代碼隨想錄算法訓練營第四十六天| 139 單詞拆分

目錄 139 單詞拆分 139 單詞拆分 class Solution { public:bool wordBreak(string s, vector<string>& wordDict) {vector<bool>dp(s.size() 1);//長度為i的字符串時能否成功拆分unordered_set<string>set(wordDict.begin(),wordDict.end());dp[0] t…

數據結構 | 查漏補缺之哈希表、最短路徑、二叉樹與森林的轉換

哈希表是什么&#xff1f; 或者說 設圖采用鄰接表的存儲結構&#xff0c;寫對圖的刪除頂點和刪除邊的算法步驟 刪除邊 刪除點 最短路徑問題 參考博文 迪杰斯特拉(Dijkstra)算法_dijkstra算法-CSDN博客 Dijkstra(迪杰斯特拉&#xff09;算法 定義一個點為源點&#xff0c;算源…

5G+AI開花結果,助力智慧安檢落地

“請帶包的乘客過機安檢&#xff01;”&#xff0c;深圳地鐵、騰訊共同打造的5GAI智慧安檢輔助系統亮相福田樞紐站&#xff0c;進一步解放了人力&#xff0c;提高安檢效率&#xff0c;為交通安全保駕護航&#xff0c;讓智慧出行成為現實。 傳統的安檢設備均為人工肉眼辨識&…

java面試題匯總-目錄

堅持記錄和總結一些面試過程中遇到的面試題&#xff0c;以及總結出自己的回答技巧。不用死記硬背也能完整的回答出來。會持續更新&#xff0c;歡迎提出問題和疑問&#xff0c;大家一起總結經驗。 1.Hashmap、Hashtable、ConcurrentHashMap原理 2.談談sql優化-mysql 3.ArrayList…

2023年9月13日 Go生態洞察:WASI支持在Go中的實現

&#x1f337;&#x1f341; 博主貓頭虎&#xff08;&#x1f405;&#x1f43e;&#xff09;帶您 Go to New World?&#x1f341; &#x1f984; 博客首頁——&#x1f405;&#x1f43e;貓頭虎的博客&#x1f390; &#x1f433; 《面試題大全專欄》 &#x1f995; 文章圖文…

21、命令執行

文章目錄 一、命令執行概述1.1 基本定義1.2 原理1.3 兩個條件1.4 命令執行漏洞產生的原因1.5 管道符號和通用命令符 二、遠程命令執行2.1 遠程命令執行相關函數2.2 遠程命令執行漏洞的利用 三、系統命令執行3.1 相關函數3.2 系統命令執行漏洞利用 四、命令執行漏洞防御 一、命令…

Vue筆記(三)深入組件

組件注冊 組件注冊有兩種方式&#xff1a; 全局注冊 可以使用Vue應用實例的.component()方法&#xff0c;讓組件在當前Vue應用中全局可用&#xff0c;.component()方法可以被鏈式調用。全局注冊的組件可以在此應用的任意組件的模版中使用。import { createApp } from vue imp…

阿里云生態離線數倉

1. 大數據開發治理平臺 DataWorks 功能齊全&#xff1a;10多年大數據建設沉淀完整的平臺&#xff0c;覆蓋數據開發治理的全生命周期 簡單易用&#xff1a;全圖形化界面&#xff0c;SQL為主的數據開發方式 安全穩定&#xff1a;雙11日千萬級任務穩定調度&#x…

一:C語言常見概念

一&#xff1a;C語言常見概念 1.認識C語言&#xff1a; ? C語言是人和計算機交流的語言 ? C語言是一門面向過程的語言&#xff0c;而C&#xff0c;Java&#xff0c;Python等是一門面向對象的語言 ? 軟件開發&#xff08;項目&#xff09;&#xff1a;面向過程面向對象 …

maven下載安裝與配置

文章目錄 1. Maven下載2. 配置settings.xml2.1 指定Maven的本地倉庫2.2 配置阿里云提供的鏡像倉庫2.3 配置 Maven 工程的基礎 JDK 版本 3. 配置環境變量3.1 檢查 JAVA_HOME 配置是否正確3.2 配置 MAVEN_HOME3.3 配置PATH3.4 驗證 1. Maven下載 【Maven官網地址】 【Maven下載…