java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot Spring Retry接口重试

SpringBoot整合Spring Retry优雅实现接口重试的示例代码

作者:张老师技术栈

接口调用失败时直接返回错误不是最佳选择,有些场景重试一下就成功了,本文详细介绍Spring Retry的声明式重试机制,包括引入依赖、开启重试、使用@Retryable、自定义重试策略、编程式重试与配置,需要的朋友可以参考下

接口调用失败时,直接返回错误不是最佳选择,有些场景重试一下就成功了。Spring Retry 提供了声明式重试机制。

一、引入依赖

<dependency>
    <groupId>org.springframework.retry</groupId>
    <artifactId>spring-retry</artifactId>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
</dependency>

二、开启重试

@SpringBootApplication
@EnableRetry
public class SeckillApplication {
    public static void main(String[] args) {
        SpringApplication.run(SeckillApplication.class, args);
    }
}

三、使用 @Retryable

@Service
public class PaymentService {

    private static final Logger log = LoggerFactory.getLogger(PaymentService.class);

    @Retryable(
        value = {RemoteAccessException.class, TimeoutException.class},
        maxAttempts = 3,
        backoff = @Backoff(delay = 1000, multiplier = 2)
    )
    public boolean refund(String orderNo) {
        log.info("退款请求: {}", orderNo);
        // 调用第三方支付接口
        return thirdPartyRefund(orderNo);
    }

    @Recover
    public boolean recover(RemoteAccessException e, String orderNo) {
        log.error("退款失败,记录到异常表: {}", orderNo, e);
        // 记录到失败表,人工处理
        return false;
    }
}

四、自定义重试策略

@Configuration
public class RetryConfig {

    @Bean
    public RetryTemplate retryTemplate() {
        RetryTemplate template = new RetryTemplate();

        // 重试策略:最多重试5次,间隔递增
        ExponentialBackOffPolicy backOff = new ExponentialBackOffPolicy();
        backOff.setInitialInterval(1000);
        backOff.setMultiplier(2);
        backOff.setMaxInterval(10000);
        template.setBackOffPolicy(backOff);

        // 异常判断:哪些异常需要重试
        SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
        retryPolicy.setMaxAttempts(5);
        template.setRetryPolicy(retryPolicy);

        return template;
    }
}

五、编程式重试

@Service
public class OrderService {

    @Autowired
    private RetryTemplate retryTemplate;

    public boolean processOrder(Long orderId) {
        return retryTemplate.execute(context -> {
            log.info("处理订单,第{}次尝试", context.getRetryCount() + 1);
            return doProcess(orderId);
        }, context -> {
            log.error("最终失败", context.getLastThrowable());
            return false;
        });
    }
}

六、重试配置

spring:
  retry:
    max-attempts: 3    # 全局最大重试次数

七、秒杀系统应用

@Service
public class SeckillService {

    @Retryable(
        value = OptimisticLockException.class,
        maxAttempts = 3,
        backoff = @Backoff(delay = 200)
    )
    public boolean deductStock(Long productId) {
        // 乐观锁失败时自动重试
        return productMapper.updateStock(productId) > 0;
    }
}

到此这篇关于SpringBoot整合Spring Retry优雅实现接口重试的示例代码的文章就介绍到这了,更多相关SpringBoot Spring Retry接口重试内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文