一、背景
为了学习和研究一个系统是如何演进并发展的,这里采取电商系统是因为电商系统不需要过多的解释业务背景,另外业务也会设计的相对简单,大家可以将关注点放在技术本身上。重点是研究宏观上的技术方案,以及方案对应的测试数据。
业务背景:假定用户下单后系统自动从用户余额中扣钱
二、下单流程图
2.1 业务说明
我只设计简单也,同时也简化模块功能,这里商品与订单放在一个系统,用户中心与账户放在同一个系统,所以只有2个系统,系统间的通信方式用OpenFeign + Consul
2.2 流程说明
- 用户点击下单
- 向数据库查询库存
- 库存足够就扣减库存,并创建订单(事务)
- 向用户中心发起支付请求
- user-center查询用户余额
- 若余额充足,则进行转账动作
- 转账成功后返回给goods-center
- goods-center 更新订单状态为交易成功
三、数据库表设计
CREATE DATABASE user_center_db;
CREATE DATABASE goods_center_db;
CREATE TABLE user_center_db.user_info_tab (
`id` BIGINT(20) NOT NULL,
`nick_name` VARCHAR(20) NOT NULL,
`age` int(11) NOT NULL,
`balance` DECIMAL(20,5) NOT NULL COMMENT '余额',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT '用户信息表';
CREATE TABLE user_center_db.account_flow_tab (
`id` BIGINT(20) NOT NULL,
`order_id` BIGINT(20) NOT NULL COMMENT '订单ID',
`src_account_id` BIGINT(20) NOT NULL COMMENT '转出账户' ,
`target_account_id` BIGINT(20) NOT NULL COMMENT '转入账户' ,
`transfer_amount` DECIMAL(20,5) NOT NULL COMMENT '转账金额',
`src_before_balance` DECIMAL(20,5) NOT NULL COMMENT '转出账户转前余额',
`src_after_balance` DECIMAL(20,5) NOT NULL COMMENT '转出账户转后余额',
`target_before_balance` DECIMAL(20,5) NOT NULL COMMENT '转入账户转前余额',
`target_after_balance` DECIMAL(20,5) NOT NULL COMMENT '转入账户转后余额',
`transfer_time` datetime NOT NULL COMMENT '转账时间',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE,
KEY `idx_order_id` (`order_id`),
KEY `idx_src_account_id` (`src_account_id`),
KEY `idx_target_account_id` (`target_account_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT '账户流水表';
CREATE TABLE goods_center_db.goods_info_tab (
`id` BIGINT(20) NOT NULL,
`goods_name` VARCHAR(30) NOT NULL COMMENT '商品名称',
`seller_id` BIGINT(20) NOT NULL COMMENT '卖家ID',
`stock` int(11) NOT NULL COMMENT '库存',
`sold` int(11) NOT NULL COMMENT '已售数量',
`price` DECIMAL(20,5) NOT NULL COMMENT '单价',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE,
KEY `idx_seller_id` (`seller_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT '商品表';
CREATE TABLE goods_center_db.order_info_tab (
`id` BIGINT(20) NOT NULL,
`goods_id` BIGINT(20) NOT NULL COMMENT '商品ID',
`goods_name` VARCHAR(32) NOT NULL COMMENT '商品名称',
`trade_number` int(11) NOT NULL COMMENT '交易数量',
`seller_id` BIGINT(20) NOT NULL COMMENT '卖家ID',
`buyer_id` BIGINT(20) NOT NULL COMMENT '买家ID',
`order_amount` DECIMAL(20,5) NOT NULL COMMENT '订单金额=单价*数量',
`order_status` TINYINT(4) NOT NULL COMMENT '订单状态: 1 创建中, 2 支付中, 3 支付成功, 11 已取消, 11 支付失败',
`order_msg` VARCHAR(64) NOT NULL COMMENT '订单信息,描述订单失败或取消原因',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE,
KEY `idx_goods_id` (`goods_id`),
KEY `idx_seller_id` (`seller_id`),
KEY `idx_buyer_id` (`buyer_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT '订单表';
四、代码编写
按照上述流程图我们开始编写自己的代码
4.1 代码的gitee地址
4.2 核心代码精选
a 提交订单的主流程
@Override
public OrderInfo submitOrder(SubmitOrderReq req) {
//库存足够就扣减库存,并创建订单(事务)
OrderInfo orderInfo = orderBizService.reduceStockAndCreateOrder(req);
//向用户中心发起支付请求
PayForOrderReq payForOrderReq = buildPayForOrderReq(orderInfo);
PayForOrderResp resp = accountFacade.payForOrder(payForOrderReq);
if (!resp.getIsSuccess()) {
// 支付失败
orderBizService.rollbackStockAndUpdateOrder(orderInfo);
} else {
// 支付成功
orderInfo.setOrderStatus(OrderStatusEnum.PAID.getCode());
orderInfoMapper.updateOrderStatusByPrimaryKey(orderInfo.getId(), orderInfo.getOrderStatus());
}
return orderInfo;
}
b 减少库存并创建订单(事务)
// 减少库存并创建订单
@Transactional(rollbackFor = {Exception.class})
public OrderInfo reduceStockAndCreateOrder(SubmitOrderReq req) {
//向数据库查询库存,并加锁
GoodsInfo goodsInfo = goodsInfoMapper.selectByPrimaryKey(req.getGoodsId(), true);
// 检查库存
if (goodsInfo.getStock() < req.getTradeNumber()) {
throw new RuntimeException("stock not enough");
}
// 扣减库存
goodsInfoMapper.reduceStock(req.getGoodsId(), req.getTradeNumber());
// 创建订单
OrderInfo orderInfo = buildOrderInfo(req, goodsInfo);
orderInfoMapper.insert(orderInfo);
return orderInfo;
}
c 支付失败回滚库存
// 回滚库存并且更新订单
@Transactional(rollbackFor = {Exception.class})
public void rollbackStockAndUpdateOrder(OrderInfo orderInfo) {
// 回滚库存
goodsInfoMapper.rollbackStock(orderInfo.getGoodsId(), orderInfo.getTradeNumber());
// 创建订单
orderInfo.setOrderStatus(OrderStatusEnum.PAYMENT_FAILED.getCode());
orderInfoMapper.updateOrderStatusByPrimaryKey(orderInfo.getId(), orderInfo.getOrderStatus());
}
d 支付代码(幂等和事务)
@Override
@Transactional(rollbackFor = {Exception.class})
public PayForOrderResp payForOrder(PayForOrderReq req) {
PayForOrderResp resp = new PayForOrderResp();
// 幂等处理,查询是否已经有流水了
AccountFlow flow = accountFlowMapper.selectByOrderId(req.getOrderId());
if (flow != null) {
resp.setIsSuccess(true);
return resp;
}
UserInfo srcAccount = userInfoMapper.selectByPrimaryKey(req.getSrcAccountId(), true);
// 余额不足
if (srcAccount.getBalance().compareTo(req.getTransferAmount()) < 0) {
resp.setIsSuccess(false);
resp.setMsg("amount not enough");
return resp;
}
UserInfo targetAccount = userInfoMapper.selectByPrimaryKey(req.getTargetAccountId(), true);
BigDecimal srcBeforeBalance = srcAccount.getBalance();
BigDecimal targetBeforeBalance = targetAccount.getBalance();
//若余额充足,则进行转账动作
srcAccount.setBalance(srcAccount.getBalance().subtract(req.getTransferAmount()));
targetAccount.setBalance(targetAccount.getBalance().add(req.getTransferAmount()));
userInfoMapper.updateByPrimaryKey(srcAccount);
userInfoMapper.updateByPrimaryKey(targetAccount);
BigDecimal srcAfterBalance = srcAccount.getBalance();
BigDecimal targetAfterBalance = targetAccount.getBalance();
flow = genAccountFlow(req, srcBeforeBalance, targetBeforeBalance, srcAfterBalance, targetAfterBalance);
accountFlowMapper.insert(flow);
resp.setIsSuccess(true);
return resp;
}
五、主流程测试
5.1 造数(代码写在单元测试目录下)
a 初始化用户
private void intUser() {
List<UserInfo> list = new ArrayList<>();
int batchSize = 200;
for (int i = 1; i <= 1000; i++) {
UserInfo userInfo = new UserInfo();
userInfo.setId(SnowFlakeUtils.nextId());
userInfo.setNickName("机器人~" + i);
userInfo.setAge(10);
userInfo.setBalance(new BigDecimal(10000));
list.add(userInfo);
if (i % batchSize == 0) {
userInfoMapper.batchInsert(list);
list = new ArrayList<>();
}
}
}
b 初始化商品
sellerId 从前面生成好的用户数据中,选一个作为商品的卖家
private void intGoods() {
List<GoodsInfo> list = new ArrayList<>();
int batchSize = 200;
for (int i = 1; i <= 1000; i++) {
GoodsInfo goodsInfo = new GoodsInfo();
goodsInfo.setId(SnowFlakeUtils.nextId());
goodsInfo.setGoodsName("虚拟商品~" + i);
goodsInfo.setSellerId(8436039040700628992L);
goodsInfo.setStock(100_0000);
goodsInfo.setSold(0);
goodsInfo.setPrice(new BigDecimal(1));
list.add(goodsInfo);
if (i % batchSize == 0) {
goodsInfoMapper.batchInsert(list);
list = new ArrayList<>();
}
}
}
5.2 执行
所有的数据都正确,主流程测试成功(说明:因为代码刚刚开始也是有少量bug的,我进行了多次调试,金额是经过多次转账的,所以看到的金额可能有点奇怪,最后的操作我验证过是正确的)
下篇文章,我将进行压力测试,看看在这种架构下系统的支持的并发请求数是多少,并分析原因!!!