mybatis请求重试工具
int maxRetries = 3;
long retryIntervalMs = 1000;for (String item : Arrays.asList("item1", "item2", "item3")) {int attempt = 0;boolean success = false;while (attempt < maxRetries && !success) {try {// 模拟可能失败的更新操作updateItem(item);success = true;} catch (Exception e) {attempt++;if (attempt >= maxRetries) {System.err.println("更新 " + item + " 失败,已达最大重试次数");break;}try {Thread.sleep(retryIntervalMs);} catch (InterruptedException ignored) {}}}if (success) {System.out.println("成功更新: " + item);}
}
Mybatis请求
package com.ldj.springboot.importbean.utils;/*** User: ldj* Date: 2025/10/21* Time: 23:52* Description: No Description*/
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.util.function.Function;public class MyBatisRetryHelper {private static final Logger log = LoggerFactory.getLogger(MyBatisRetryHelper.class);private final SqlSessionFactory sqlSessionFactory;private final int maxRetries;private final long retryIntervalMs;public MyBatisRetryHelper(SqlSessionFactory sqlSessionFactory, int maxRetries, long retryIntervalMs) {this.sqlSessionFactory = sqlSessionFactory;this.maxRetries = maxRetries;this.retryIntervalMs = retryIntervalMs;}/*** 重试直到操作返回的影响行数 > 0*/public boolean retryOnZeroUpdate(Function<SqlSession, Integer> updateOperation, String itemName) {try (SqlSession session = sqlSessionFactory.openSession()) {for (int attempt = 1; attempt <= maxRetries; attempt++) {Integer affectedRows = null;try {affectedRows = updateOperation.apply(session);if (affectedRows != null && affectedRows > 0) {log.info("更新成功: {}, 影响行数: {}, 尝试次数: {}", itemName, affectedRows, attempt);session.commit(); // 提交事务return true;} else {log.warn("更新失败(影响行数为0): {}, 重试 {}/{}", itemName, attempt, maxRetries);}} catch (Exception e) {log.error("更新异常: " + itemName, e);}// 重试前等待if (attempt < maxRetries) {try {Thread.sleep(retryIntervalMs);} catch (InterruptedException ignored) {Thread.currentThread().interrupt();return false;}}}log.error("更新 {} 失败:已达最大重试次数", itemName);return false;}}
}
使用方式:Spring / Spring Boot 环境
@Service
public class OrderService {@Autowiredprivate SqlSessionFactory sqlSessionFactory;private MyBatisRetryHelper retryHelper;@PostConstructpublic void init() {this.retryHelper = new MyBatisRetryHelper(sqlSessionFactory, 3, 1000);}// 后续业务方法...
}// 要处理的订单 ID 列表
List<String> orderIds = Arrays.asList("O1001", "O1002", "O1003");for (String orderId : orderIds) {boolean success = retryHelper.retryOnZeroUpdate(session -> {// 获取 Mapper 并执行更新OrderMapper mapper = session.getMapper(OrderMapper.class);return mapper.updateOrderStatus(orderId, "PROCESSED");}, orderId); // itemName 用于日志输出if (success) {System.out.println("成功处理订单: " + orderId);} else {System.err.println("最终失败,无法处理订单: " + orderId);// 可选:记录到失败表、发告警、进死信队列等}
}