007 SpringBoot-整合重试策略详解

SpringBoot 重试机制

        Retry重试机制,其实就是我们对一个请求进行多次重试,可以指定重试的相关参数,例如重试次数、间隔、重试线程数等等,什么异常情况下进行重试,如果达到指定上限可以进行具体的最终性失败处理。

第一步引入依赖:

第二步:@EnableRetry 启用重试功能

第三步:@Retryable 在方法上配置重试机制,相关核心配置参数如下

value 指定异常进行重试策略的执行

maxAttempts 重试次数

Backoff @Backoff(delay = 5000, multiplier = 5)) 重试间隔 线程并行度

第四步:@Recover 最终失败处理方法

实现:

package com.cc.springboot.service;

import java.util.concurrent.TimeoutException;

import org.springframework.remoting.RemoteAccessException;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.EnableRetry;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

@EnableRetry
@Service
public class RetryService {
    @Retryable(
            //配置value什么类型异常进行重试
            value = {RemoteAccessException.class,TimeoutException.class},
            maxAttempts = 3, //重试次数
            backoff = @Backoff(delay = 2000,multiplier = 5)
            )
    public void call() throws Exception{
        System.out.println("执行了call方法...");
        //RPC服务调用,(timeout...)
        //不可能同时捕获两种异常,所以进行切换测试
        //throw new RemoteAccessException("rpc调用异常...");
        throw new TimeoutException("超时异常...");
    }
    //3次重试失败后的补充策略,实际环境中自定义异常,继承
    @Recover
    public void recover(RemoteAccessException re) {
        System.out.println("最终重试失败,进行补偿:"+re.getMessage());
    }
    @Recover
    public void recover(TimeoutException te) {
        System.out.println("最终重试失败,进行补偿:"+te.getMessage());
    }
}
 

package com.cc.springboot;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.cc.springboot.service.RetryService;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {

    @Test
    public void contextLoads() {
    }
    
    @Autowired
    private RetryService retryService;
    
    @Test
    public void testRetry() throws Exception{
        retryService.call();
    }

}
输出结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值