乐观锁实现重试机制
//乐观锁冲突最大重试次数
private static final int DEFAULT_MAX_RETRIES = 5;
/**
* 减少库存,每次减一
*
* @return
*/
public boolean reduceStock(GoodsVo goods) {
int numAttempts = 0;
int ret = 0;
SeckillGoods sg = new SeckillGoods();
sg.setGoodsId(goods.getId());
sg.setVersion(goods.getVersion());
do {
numAttempts++;
try {
sg.setVersion(goodsMapper.getVersionByGoodsId(goods.getId()));
ret = goodsMapper.reduceStockByVersion(sg);
} catch (Exception e) {
e.printStackTrace();
}
if (ret != 0)
break;
} while (numAttempts < DEFAULT_MAX_RETRIES);
return ret > 0;
}
@Mapper
public interface GoodsMapper {
//stock_count > 0 和 版本号实现乐观锁 防止超卖
@Update("update sk_goods_seckill set stock_count = stock_count - 1, version= version + 1 where goods_id = #{goodsId} and stock_count > 0 and version = #{version}")
public int reduceStockByVersion(SeckillGoods seckillGoods);
// 获取最新版本号
@Select("select version from sk_goods_seckill where goods_id = #{goodsId}")
public int getVersionByGoodsId(@Param("goodsId") long goodsId);
}