Spring Retry 实现乐观锁重试
一、场景分析
假设有这么一张表:
create table pms_sec_kill_sku
(id int auto_increment comment '主键ID'primary key,spec_detail varchar(50) not null comment '规格描述',purchase_price decimal(10, 2) not null comment '采购价格',sale_price decimal(10, 2) not null comment '销售价格',origin_stock int unsigned default '0' not null comment '初始库存',sold_stock int unsigned default '0' not null comment '已售库存',stock int unsigned default '0' not null comment '实时库存',occupy_stock int unsigned default '0' not null comment '订单占用库存',version int default 0 not null comment '乐观锁版本号',created_time datetime not null comment '创建时间',updated_time datetime not null comment '更新时间'
)comment '促销管理服务-秒杀商品SKU';
一张简单的秒杀商品SKU表。使用 version 字段做乐观锁。使用 unsigned 关键字,限制 int 类型非负,防止库存超卖。
使用 MybatisPlus 来配置乐观锁:
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();// 分页插件interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));// 乐观锁插件interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());return interceptor;}@Beanpublic DefaultDBFieldHandler defaultDBFieldHandler() {DefaultDBFieldHandler defaultDBFieldHandler = new DefaultDBFieldHandler();return defaultDBFieldHandler;}
}
@Data
@TableName("pms_sec_kill_sku")
@ApiModel(value = "PmsSecKillSku对象", description = "促销管理-秒杀商品SKU")
public class PmsSecKillSku implements Serializable {private static final long serialVersionUID = 1L;// @Version 注解不能遗漏@Version@ApiModelProperty("乐观锁版本号")private Integer version;// other properties ......
}
现在有这么一个支付回调接口:
/*** 促销管理-秒杀商品SKU 服务实现类* @since 2025-02-26 14:21:42*/
@Service
public class PmsSecKillSkuServiceImpl extends ServiceImpl<PmsSecKillSkuMapper, PmsSecKillSku> implements PmsSecKillSkuService {// 最大重试次数private static final int MAX_RETRIES = 3;/*** 订单支付成功回调* 假设每次只能秒杀一个数量的SKU*/@Override@Transactional(rollbackFor = Exception.class)public void paySucCallback(Integer skuId) {// 持久化库存int count = 0, retries = 0;while (count == 0 && retries < MAX_RETRIES) {PmsSecKillSkuVo pmsSkuVo = this.baseMapper.findDetailById(skuId);PmsSecKillSku wt = new PmsSecKillSku();wt.setId(pmsSkuVo.getId());wt.setVersion(pmsSkuVo.getVersion());// 占用库存减1wt.setOccupyStock( pmsSkuVo.getOccupyStock()-1 );// 已售库存加1wt.setSoldStock( pmsSkuVo.getSoldStock()+1 );// 实时库存减1wt.setStock( pmsSkuVo.getStock()-1 );count = this.baseMapper.updateById(wt);retries++;if (count == 0) {try {Thread.sleep(100);} catch (InterruptedException e) {throw new BusinessException(e.getMessage());}}}if (count == 0) {throw new BusinessException("请刷新后重新取消!");}}}
该方法的目的,是为了进行库存更新,当乐观锁版本号有冲突时,对方法进行休眠重试。
该方法在测试环境还能正常跑,到了生产环境,却频繁报 "请刷新后重新取消!"
仔细分析后发现,测试环境的MYSQL数据库全局隔离级别是,READ-COMMITTED(读已提交)。而生产环境是 REPEATABLE_READ(可重复读)。
SHOW GLOBAL VARIABLES LIKE 'transaction_isolation';
- 在读已提交隔离级别下,该方法每次重试,都能读取到别的事务提交的最新的 version,相当于拿到乐观锁。
- 在可重复读隔离级别下,因为有 MVCC 多版本并发控制,该方法每次重试,读取到的都是同一个结果,相当于一直拿不到乐观锁。所以多次循环之后,count 还是等于 0,程序抛出异常。
二、简单验证
假设现在表里面有这么一条记录:
INSERT INTO `pms_sec_kill_sku`
(`id`, `spec_detail`, `purchase_price`, `sale_price`,
`origin_stock`, `sold_stock`, `stock`, `occupy_stock`,
`version`, `created_time`, `updated_time`) VALUES
(1, '尺码:M1', 100.00, 1.00,
2, 0, 2, 2,
2, '2025-02-26 15:51:22', '2025-02-26 15:51:24');
2.1、可重复读
修改服务程序:
- 增加会话的隔离级别为 isolation = Isolation.REPEATABLE_READ 可以重复读。
- 增加记录日志。
- 在方法更新前阻塞当前线程,模拟另一个事务先提交。
@Api(value = "促销管理-秒杀商品SKU", tags = {"促销管理-秒杀商品SKU接口"})
@RestController
@RequiredArgsConstructor
@RequestMapping("pmsSecKillSku")
public class PmsSecKillSkuController {private final PmsSecKillSkuService pmsSecKillSkuService;@ApiOperation(value = "支付成功", notes = "支付成功")@PostMapping("/pay")public R<Void> pay(Integer id) {pmsSecKillSkuService.paySucCallback(id);return R.success();}
}
访问接口:
###
POST http://localhost:5910/pmsSecKillSku/pay?id=1
Content-Type: application/json
token: 123
在第0次查询的时候,执行更新:
UPDATE `pms_sec_kill_sku`
SET sold_stock = sold_stock + 1, stock = stock - 1,
occupy_stock = occupy_stock - 1, version = version + 1
WHERE id = 1;
可以看到,三次查询,返回结果都是一样的:
数据库的版本号只有3:
2.2、读已提交
修改会话的隔离级别为 isolation = Isolation.READ_COMMITTED 读已提交。
恢复数据:
访问接口:
###
POST http://localhost:5910/pmsSecKillSku/pay?id=1
Content-Type: application/json
token: 123
在第0次查询的时候,执行更新:
UPDATE `pms_sec_kill_sku`
SET sold_stock = sold_stock + 1, stock = stock - 1,
occupy_stock = occupy_stock - 1, version = version + 1
WHERE id = 1;
可以看到,第0次查询的时候,version=2;执行完 SQL语句,第1次查询的时候,version=3;拿到了乐观锁,更新成功。
三、最佳实践
可以看到,使用 Thread.sleep 配合循环来进行获取乐观锁的重试,存在一些问题:
- 依赖事务隔离级别的正确设置。
- 休眠的时间不好把控。
- 代码复用性差。
Spring Retry 提供了一种更优雅的方式,来进行乐观锁的重试。
恢复数据:
3.1、配置重试模板
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.annotation.EnableRetry;
import org.springframework.retry.backoff.FixedBackOffPolicy;
import org.springframework.retry.support.RetryTemplate;@Configuration
@EnableRetry
public class RetryConfig {@Beanpublic RetryTemplate retryTemplate() {RetryTemplate retryTemplate = new RetryTemplate();// 设置重试策略,这里设置最大重试次数为3次SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(3);retryTemplate.setRetryPolicy(retryPolicy);// 设置重试间隔时间,这里设置为固定的500毫秒// 可以根据系统的并发度,来设置// 并发度高,设置长一点,并发度低,设置短一点FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();backOffPolicy.setBackOffPeriod(500);retryTemplate.setBackOffPolicy(backOffPolicy);return retryTemplate;}
}
3.2、使用 Spring 的@Retryable
注解
@Override@Retryable(value = OptimisticLockingFailureException.class)@Transactional(rollbackFor = Exception.class, isolation = Isolation.REPEATABLE_READ)public void paySucRetry(Integer skuId) {PmsSecKillSkuVo pmsSkuVo = this.baseMapper.findDetailById(skuId);log.info("===============查询结果为{}", pmsSkuVo);PmsSecKillSku wt = new PmsSecKillSku();wt.setId(pmsSkuVo.getId());wt.setVersion(pmsSkuVo.getVersion());// 占用库存减1wt.setOccupyStock( pmsSkuVo.getOccupyStock()-1 );// 已售库存加1wt.setSoldStock( pmsSkuVo.getSoldStock()+1 );// 实时库存减1wt.setStock( pmsSkuVo.getStock()-1 );try {Thread.sleep(10000);} catch (InterruptedException e) {throw new BusinessException(e.getMessage());}int count = this.baseMapper.updateById(wt);if (count == 0) {throw new OptimisticLockingFailureException("乐观锁冲突");}}
当乐观锁冲突的时候,抛出异常, OptimisticLockingFailureException。
这里特意设置事务隔离级别为 REPEATABLE_READ
3.3、测试
访问接口:
@Api(value = "促销管理-秒杀商品SKU", tags = {"促销管理-秒杀商品SKU接口"})
@RestController
@RequiredArgsConstructor
@RequestMapping("pmsSecKillSku")
public class PmsSecKillSkuController {private final PmsSecKillSkuService pmsSecKillSkuService;@ApiOperation(value = "可重试", notes = "可重试")@PostMapping("/retry")public R<Void> retry(Integer id) {pmsSecKillSkuService.paySucRetry(id);return R.success();}
}
###
POST http://localhost:5910/pmsSecKillSku/retry?id=1
Content-Type: application/json
token: 123
在第0次查询的时候,执行更新:
UPDATE `pms_sec_kill_sku`
SET sold_stock = sold_stock + 1, stock = stock - 1,
occupy_stock = occupy_stock - 1, version = version + 1
WHERE id = 1;
可以看到,在第二次查询的时候,就获取到锁,并成功执行更新。