当前位置: 首页 > news >正文

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 {
    
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        // 乐观锁插件
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }

    @Bean
    public 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());
            // 占用库存减1
            wt.setOccupyStock( pmsSkuVo.getOccupyStock()-1 );
            // 已售库存加1
            wt.setSoldStock( pmsSkuVo.getSoldStock()+1 );
            // 实时库存减1
            wt.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、可重复读

 修改服务程序:

  1. 增加会话的隔离级别为 isolation = Isolation.REPEATABLE_READ 可以重复读。
  2. 增加记录日志。
  3. 在方法更新前阻塞当前线程,模拟另一个事务先提交。
@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 {

    @Bean
    public 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());
        // 占用库存减1
        wt.setOccupyStock( pmsSkuVo.getOccupyStock()-1 );
        // 已售库存加1
        wt.setSoldStock( pmsSkuVo.getSoldStock()+1 );
        // 实时库存减1
        wt.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;

可以看到,在第二次查询的时候,就获取到锁,并成功执行更新。

相关文章:

  • 【数据结构】二叉树(门槛极低的系统性理解)
  • React进阶之前端业务Hooks库(四)
  • 2.27-1笔记1
  • 【Vue3 Teleport 技术解析:破解弹窗吸附与滚动列表的布局困局】
  • 初阶数据结构(C语言实现)——3顺序表和链表(2)
  • linux--多进程开发(6)IPC之内存映射
  • thinkphp下的Job队列处理
  • 网络运维学习笔记(DeepSeek优化版)006网工初级(HCIA-Datacom与CCNA-EI)VLAN间路由
  • Android手机部署DeepSeek
  • C# Json序列化的常用几种方式
  • 教你通过腾讯云AI代码助手,免费使用满血版deepseek r1,还可以自定义知识库!
  • AF3 pair_sequences函数解读
  • 2月27(信息差)
  • Spock框架:让单元测试更优雅的高效武器
  • 【nextjs官方demo】Chapter 6连接数据库报错
  • docker 运行claude 的computer use
  • Linux驱动学习(四)--字符设备注册
  • MySQL练习
  • AI人工智能机器学习之降维和数据压缩
  • 基于W2605C语音识别合成芯片的智能语音交互闹钟方案-AI对话享受智能生活
  • 网站建设与app开发/seo外链网
  • 连接品硕网线做怎么弹网站/全网引流推广
  • 重庆seo团队/aso如何优化
  • 建设工程质量+协会网站/互联网项目推广平台有哪些
  • 肇庆微网站/网站快速收录技术
  • 深圳建设门户网站/中山疫情最新消息