为了学习和研究一个系统是如何演进并发展的,这里采取电商系统是因为电商系统不需要过多的解释业务背景,另外业务也会设计的相对简单,大家可以将关注点放在技术本身上。重点是研究宏观上的技术方案,以及方案对应的测试数据。
业务背景:假定用户下单后系统自动从用户余额中扣钱
我只设计简单也,同时也简化模块功能,这里商品与订单放在一个系统,用户中心与账户放在同一个系统,所以只有2个系统,系统间的通信方式用OpenFeign + Consul
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 '订单表';
按照上述流程图我们开始编写自己的代码
风萧萧兮/concurrency-entry-task
@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;
}
// 减少库存并创建订单
@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;
}
// 回滚库存并且更新订单
@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());
}
@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;
}
private void intUser() {
List 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<>();
}
}
}
sellerId 从前面生成好的用户数据中,选一个作为商品的卖家
private void intGoods() {
List 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的,我进行了多次调试,金额是经过多次转账的,所以看到的金额可能有点奇怪,最后的操作我验证过是正确的)
下篇文章,我将进行压力测试,看看在这种架构下系统的支持的并发请求数是多少,并分析原因!!!