当前位置:首页 > 技术 > 正文内容

商城系统购物车逻辑优化:避免下单重复提交问题

访客 技术 2026年7月31日 1

问题背景

在电商系统中,购物车操作需要特别注意幂等性问题。用户在提交订单时可能会因为网络延迟或操作重复导致重复下单,这需要我们在系统设计中加入幂等性保护机制。

购物车控制器逻辑

package com.mall.shoppingcart.controller;

import com.mall.shoppingcart.service.ShoppingCartService;
import com.mall.shoppingcart.vo.ShoppingCartItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.concurrent.ExecutionException;

@Controller
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;

    @GetMapping("/addToCart")
    public String addToCart(@RequestParam("productId") Long productId, @RequestParam("amount") Integer amount, RedirectAttributes model) throws ExecutionException, InterruptedException {
        if(amount > 0) {
            ShoppingCartItem cartItem = shoppingCartService.addProductToCart(productId, amount);
            model.addAttribute("productId", productId);
            return "redirect:http://cart.mall.com/addToCartSuccess.html";
        }
        return "redirect:http://cart.mall.com/addToCartSuccess.html";
    }

    @GetMapping("/addToCartSuccess.html")
    public String addToCartSuccessPage(@RequestParam("productId") Long productId, Model model) {
        ShoppingCartItem cartItem = shoppingCartService.getProductFromCart(productId);
        model.addAttribute("item", cartItem);
        return "success";
    }
}

购物车服务接口

package com.mall.shoppingcart.service;

import com.mall.shoppingcart.vo.ShoppingCartItem;

public interface ShoppingCartService {
    ShoppingCartItem addProductToCart(Long productId, Integer amount) throws ExecutionException, InterruptedException;

    ShoppingCartItem getProductFromCart(Long productId);
}

购物车服务实现

package com.mall.shoppingcart.service.impl;

import com.mall.common.utils.R;
import com.mall.shoppingcart.feign.ProductFeignService;
import com.mall.shoppingcart.service.ShoppingCartService;
import com.mall.shoppingcart.vo.ShoppingCartItem;
import com.mall.shoppingcart.vo.ProductInfoVo;
import com.mall.shoppingcart.vo.UserContext;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private ThreadPoolExecutor executor;
    private final String SHOPPING_CART_PREFIX = "mallshoppingcart:";

    @Override
    public ShoppingCartItem addProductToCart(Long productId, Integer amount) throws ExecutionException, InterruptedException {
        BoundHashOperations cartOps = getCartOperations();
        String existingItem = (String) cartOps.get(productId.toString());
        
        if (StringUtils.isEmpty(existingItem)) {
            ShoppingCartItem newItem = new ShoppingCartItem();
            CompletableFuture<Void> getProductInfo = CompletableFuture.runAsync(() -> {
                R info = productFeignService.fetchProductInfo(productId);
                if (info.getCode() == 0) {
                    ProductInfoVo product = info.get("product", new TypeReference<ProductInfoVo>() {});
                    newItem.setChecked(true);
                    newItem.setQuantity(amount);
                    newItem.setImage(product.getDefaultImage());
                    newItem.setTitle(product.getTitle());
                    newItem.setProductId(productId);
                    newItem.setPrice(product.getPrice());
                }
            }, executor);

            CompletableFuture<Void> getAttrValues = CompletableFuture.runAsync(() -> {
                List<String> attrs = productFeignService.fetchSkuAttrValues(productId);
                newItem.setSkuAttributes(attrs);
            }, executor);

            CompletableFuture.allOf(getProductInfo, getAttrValues).get();
            String json = JSON.toJSONString(newItem);
            cartOps.put(productId.toString(), json);
            return newItem;
        } else {
            ShoppingCartItem existingItemObj = JSON.parseObject(existingItem, ShoppingCartItem.class);
            existingItemObj.setQuantity(existingItemObj.getQuantity() + amount);
            cartOps.put(productId.toString(), JSON.toJSONString(existingItemObj));
            return existingItemObj;
        }
    }

    @Override
    public ShoppingCartItem getProductFromCart(Long productId) {
        BoundHashOperations cartOps = getCartOperations();
        String itemStr = (String) cartOps.get(productId.toString());
        return JSON.parseObject(itemStr, ShoppingCartItem.class);
    }

    private BoundHashOperations getCartOperations() {
        UserContext userContext = UserContextHolder.getContext();
        String cartKey = "";
        if (userContext.getUserId() != null) {
            cartKey = SHOPPING_CART_PREFIX + userContext.getUserId();
        } else {
            cartKey = SHOPPING_CART_PREFIX + userContext.getUserKey();
        }
        return redisTemplate.boundHashOps(cartKey);
    }
}

相关文章

Linux crontab 详解

1) crontab 是什么cron 是 Linux 的定时任务守护进程;crontab 是用来编辑/查看“按时间周期执行命令”的表(cron table)。常见两类:用户 crontab:每个用户一份(crontab -e 编辑)系统级 crontab / cron.d:可指定执行用户(/etc/crontab、/etc/cron.d/*)2) crontab 时间...

富文本里可以允许的 HTML 属性

一、所有标签默认允许的安全属性(极少)class        (可选)id           (通常建议禁用)title️ 注意:id 容易被滥用做锚点注入,很多系统直接禁用class 允许的话最好只允许固定前缀(如 editor-*)二、a 标签允许属性<a href="" t...

Mac 安装 Node.js 指南

方法一:通过官网安装包(最简单,适合初学者)如果你只是想快速安装并开始使用,这是最直接的方法。访问 Node.js 官网。页面会显示两个版本:LTS (Recommended For Most Users):长期支持版,最稳定。建议选这个。Current:最新特性版,包含最新功能但可能不够稳定。下载 .pkg 安装包并运行。按照安装向导点击“下一步”即可完成。方法二:使用 Homebrew 安装(...

Dom\HTML_NO_DEFAULT_NS 的副作用:自动加闭合标签

在使用Dom\HTMLDocument时,Dom\HTML_NO_DEFAULT_NS 将禁止在解析过程中设置元素的命名空间, 此设置是为了与DOMDocument向后兼容而存在的。当使用它时,已知的一个副作用就是:自动加闭合标签例如 </img> 为什么会这样?当你使用:Dom\HTML_NO_DEFAULT_NS文档会变成 无命名空间模式,此时内部更接近 XML...

Laravel 事件和监听器创建

在 Laravel 中,使用 Artisan 命令创建 Events(事件) 和 Listeners(监听器) 是非常高效的。你可以通过以下几种方式来实现:1. 手动创建单个 Event如果你只想创建一个事件类,可以使用 make:event 命令:Bashphp artisan make:event UserRegistered执行后,文件将生成在 app/Even...

linux screen 用法详情 (nohup 的替代方案)

一、screen 是什么?能干嘛?screen 是一个终端复用器,可以:在一个 SSH 会话中开多个“虚拟终端”SSH 断线后,程序仍然在后台运行随时重新连接到原来的会话特别适合:nohup 的替代方案跑脚本 / 爬虫 / 训练模型运维、远程开发二、安装 screen# CentOS / Rocky / Almayum install -y screen# Debian / Ubuntuapt i...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。