如何编写 MyBatis 插件自动重试 `1213` 死锁错误?
解读
国内互联网高并发场景下,MySQL 报 1213 Deadlock found when trying to get lock 是常态。业务侧若直接抛异常,用户体验与订单成功率都会受损,因此**“自动重试”**几乎成了面试必考点。面试官想确认两点:
- 你是否真的写过 MyBatis 插件,知道
Interceptor的签名、责任链顺序与Invocation.proceed()的底层原理; - 你是否理解死锁重试的**“有限次数 + 指数退避 + 仅重试写 SQL”**三大原则,而不是无脑
while(true)。
知识点
- MyBatis 插件机制
- 核心接口:
org.apache.ibatis.plugin.Interceptor - 签名注解:
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})}) - 责任链:四大对象(Executor、ParameterHandler、ResultSetHandler、StatementHandler)按序包装,插件通过
Plugin.wrap(target, this)生成 JDK 动态代理。
- 核心接口:
- 死锁错误码
- MySQL 错误码
1213,SQLState40001;需通过SQLException.getErrorCode()精确判断,避免误杀其他异常。
- MySQL 错误码
- 重试策略
- 上限:国内大厂普遍3 次(含首次),超过即向上抛,防止雪崩;
- 退避:首次 50 ms,第二次 100 ms,第三次 200 ms,总耗时 < 500 ms,接口超时一般 1 s;
- 写操作限定:仅对
INSERT/UPDATE/DELETE重试,SELECT不参与,防止快照读放大。
- 事务边界
- 插件只能感知到
Executor.update(),事务提交在外层 Service,因此重试必须在同一事务内重新执行 SQL;若使用 Spring 声明式事务,需确保Propagation.REQUIRED不会开启新事务。
- 插件只能感知到
- 线程安全
- 插件实例是单例,禁止在插件内维护可变状态;重试次数用方法局部变量即可。
答案
给出可直接落地的插件代码与 Spring Boot 启用方式,关键行已加粗:
@Intercepts({
@Signature(type = Executor.class, method = "update",
args = {MappedStatement.class, Object.class})
})
public class DeadlockRetryPlugin implements Interceptor {
private static final int MAX_RETRY = 3;
private static final long BASE_SLEEP = 50L; // ms
@Override
public Object intercept(Invocation invocation) throws Throwable {
int retryCount = 0;
Exception lastException;
do {
try {
**return invocation.proceed();**
} catch (Exception ex) {
lastException = ex;
if (!isDeadlock(ex)) {
throw ex;
}
retryCount++;
if (retryCount >= MAX_RETRY) {
throw new RuntimeException("Still deadlock after " + MAX_RETRY + " retries", ex);
}
**Thread.sleep(BASE_SLEEP * (1L << (retryCount - 1)));**
}
} while (true);
}
private boolean isDeadlock(Throwable ex) {
while (ex != null) {
if (ex instanceof SQLException) {
SQLException sqle = (SQLException) ex;
**if (sqle.getErrorCode() == 1213 || "40001".equals(sqle.getSQLState())) {
return true;
}**
}
ex = ex.getCause();
}
return false;
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
// 可扩展读取配置
}
}
Spring Boot 启用:
mybatis:
configuration:
**default-executor-type: reuse** # 避免 SIMPLE 每次新建连接
@Configuration
@AutoConfigureAfter(MybatisAutoConfiguration.class)
public class MyBatisPluginConfig {
@Bean
public DeadlockRetryPlugin deadlockRetryPlugin() {
return new DeadlockRetryPlugin();
}
}
使用注意
- 仅对
Executor.update()生效,批量操作Executor.query()不走此插件; - 若项目已接入 ShardingSphere、TDDL 等中间件,插件顺序需放在最外层,否则中间件提前转换异常类型会导致
1213被吞掉; - 高并发秒杀场景建议把重试逻辑上移到应用层,配合 Redis 令牌队列,插件重试只作为兜底。
拓展思考
- 如何与 Spring Retry 注解协同?
插件层做快速失败(1~2 次),应用层用@Retryable(value = DeadlockLoserDataAccessException.class, maxAttempts = 3, backoff = @Backoff(delay = 100, multiplier = 2))做慢速重试,形成二级防护。 - 如何支持批量
INSERT ... ON DUPLICATE KEY UPDATE?
批量 SQL 一次网络往返包含多行,死锁可能发生在中间某行,插件无法拆分重试;此时需把批量拆成分批提交(如 200 条一批),在业务层控制。 - 如何监控重试率?
在插件内注入 Micrometer 的Counter,标签带methodName、retryCount,通过 Grafana 看板告警重试率 > 5% 即说明索引或事务粒度设计不合理,需 DBA 介入。