数据库乐观锁 - 更新库存
在电商项目中,订单支付后,需要扣库存数量,为了防止超卖现象一般会在具体的方法中使用分布式锁,如 redisson ,同时在 sql语句中可以使用乐观锁。
// synchronized 不推荐使用,集群下无用,性能低下
// 锁数据库: 不推荐,导致数据库性能低下
// 分布式锁 zookeeper redis
使用乐观锁:
判断库存数量(stock)大于扣减数量(pendingCounts),大于才会更新sql.
stock >= #{pendingCounts}
<update id="decreaseItemSpecStock">
update
items_spec
set
stock = stock - #{pendingCounts}
where
id = #{specId}
and
stock >= #{pendingCounts}
</update>
同时在Java代码中判断,如果更新失败,返回库存不足,并全部回滚代码
int result = itemsMapperCustom.decreaseItemSpecStock(specId, buyCounts);
if (result != 1) {
throw new RuntimeException("订单创建失败,原因:库存不足!");
}