You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Spring Retry中仅针对特定场景实现恢复方法?

用Spring Retry实现特定场景的恢复方法

完全可以实现,核心是借助Spring Retry提供的RecoveryCallback接口(编程式)或@Recover注解(注解式),它们专门用于在满足特定条件时提供恢复逻辑并返回替代结果,正好解决你提到的Policy无法转换结果、RetryListener不能返回值的问题。

方案一:编程式实现(基于RetryTemplate)

通过自定义RetryPolicy控制重试触发条件,搭配RecoveryCallback处理恢复逻辑,完全匹配你的场景:

// 初始化RetryTemplate
RetryTemplate retryTemplate = new RetryTemplate();

// 自定义重试策略:仅当异常判定为临时错误(code=2)时允许重试
SimpleRetryPolicy customRetryPolicy = new SimpleRetryPolicy() {
    @Override
    public boolean canRetry(RetryContext context) {
        Throwable lastException = context.getLastThrowable();
        if (lastException != null) {
            int code = analyze_thrown_exception(lastException);
            return code == 2;
        }
        return super.canRetry(context);
    }
};
retryTemplate.setRetryPolicy(customRetryPolicy);

// 设置恢复回调:处理无需重试或重试耗尽后的场景
retryTemplate.setRecoveryCallback(context -> {
    Throwable exception = context.getLastThrowable();
    int code = analyze_thrown_exception(exception);
    if (code == 1) {
        // 场景1:返回预设结果7
        return 7;
    } else {
        // 场景3:永久异常,抛出原异常
        throw new RuntimeException("永久异常无法恢复", exception);
    }
});

// 执行目标方法
try {
    int result = retryTemplate.execute(ctx -> do_something_that_may_throw_exception());
    // 处理正常返回结果
} catch (Exception e) {
    // 处理永久异常
}

方案二:注解式实现(@Retryable + @Recover)

如果偏好注解风格,可通过@Retryable指定自定义重试策略,搭配@Recover实现恢复逻辑:

@Service
@EnableRetry // 启用Spring Retry
public class BizService {

    @Retryable(retryPolicy = CustomRetryPolicy.class)
    public int do_something_that_may_throw_exception() {
        // 原有业务逻辑,可能抛出异常
    }

    // 恢复方法:参数需匹配被重试方法抛出的异常类型
    @Recover
    public int recover(Throwable exc) {
        int code = analyze_thrown_exception(exc);
        if (code == 1) {
            return 7;
        } else {
            throw new RuntimeException("永久异常无法恢复", exc);
        }
    }

    // 自定义重试策略类
    static class CustomRetryPolicy extends SimpleRetryPolicy {
        @Override
        public boolean canRetry(RetryContext context) {
            Throwable lastException = context.getLastThrowable();
            if (lastException != null) {
                int code = analyze_thrown_exception(lastException);
                return code == 2;
            }
            return super.canRetry(context);
        }
    }

    // 你的异常分析方法
    private int analyze_thrown_exception(Throwable exc) {
        // 原有异常分析逻辑,返回1、2或其他值
    }
}

场景匹配说明

  • 场景1(code=1):RetryPolicy判定不重试,直接进入恢复逻辑返回7
  • 场景2(code=2):RetryPolicy判定允许重试,触发方法重新执行
  • 场景3(默认):RetryPolicy判定不重试,恢复逻辑抛出原异常终止流程

内容的提问来源于stack exchange,提问作者piotrek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 16:42:36