• 乐观锁的实现


    public class OrderServiceImpl implements OrderService {
    @Resource
    ProductMapper productMapper;
    @Resource
    OrderMapper orderMapper;

    /**
     * 举一反三
     * 1. 生成订单号(一定要保证唯一)
     * 2. 减少库存
     * 高并发  synchronized 加锁
     *
     * @param orderDto
     * @return redis 实现分布式锁
     * 乐观锁
     * 在数据添加字段  version
     * 线程1 查询库存的时候 库存数量   版本 +1
     * 线程2 查询库存的时候 库存数量   版本 1
     * 线程1 更新库存数量 +  版本号1   version 2
     * # 表示已经有人操作过了   直接重新下单
     * 线程2 更新数据库存数量  版本号加1  作为更新的条件  where  version = 1
     */
    @Override
    @Transactional
    public String generateOrder(OrderDto orderDto) throws ServiceException {
        String orderNo = GenerateCodeUtil.createCodeNum("OR");
        List carts = orderDto.getCarts();
        //总价
        BigDecimal total = new BigDecimal(0);
        for (CartsDto cart : carts) {
            //减少库存
            int pid = cart.getPid();
            Product product = productMapper.selectById(pid);
            // 获取库存信息   10   1
            Integer stock = product.getStock();
            int num = cart.getCount();
            if (stock >= num) {
                // 减少库存
                stock -= cart.getCount();
                //更新到数据
                int i = productMapper.updateStockById(pid, stock, product.getVersion());
                if (i == 0) {
                    throw new ServiceException(ErrorStatus.SERVICE_ERROR);
                }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    // update 表名 set stock=1, version+=1 where pid=? and version=version
    // 计算总价 价格 * 数量
    BigDecimal count = new BigDecimal(cart.getCount());
    BigDecimal price = product.getPromotePrice();
    //价格 * 数量
    BigDecimal multiply = price.multiply(count);
    // total
    total.add(multiply);
    } else {
    throw new ServiceException(“库存不够”, 2000);
    }
    }
    //保存订单
    Order order = new Order();
    order.setOrderNo(orderNo);
    order.setTotal(total);
    order.setMemberId(orderDto.getMemberId());
    orderMapper.insert(order);
    // 保存定点详情
    //发起支付
    return null;
    }
    }

  • 相关阅读:
    oauth2单点登录集成
    甜蜜约会网页制作html
    RFID电网资产全寿命周期管理解决方案
    SQL基本操作1
    Redis01——Redis简介
    【论文笔记】Aleph_star
    docer安装hadoop
    优秀公共DNS服务器推荐
    Dify配置https协议
    MySQL注入绕安全狗脚本 -- MySQLByPassForSafeDog,以及端口爆破工具 -- PortBrute配置使用
  • 原文地址:https://blog.csdn.net/weixin_42277889/article/details/126193093