SpringBoot中使用@Retryable注解进行重试

SpringBoot中使用@Retryable注解进行重试

SpringBoot中使用@Retryable注解进行重试
有功能需要重试时,可以使用Spring的 @Retryable 注解.

参数含义:

value:抛出指定异常才会重试
exclude:指定不处理的异常
maxAttempts:最大重试次数,默认3次
backoff:重试等待策略,默认使用@Backoff@Backoffvalue(相当于delay)表示隔多少毫秒后重试,默认为1000L;
multiplier(指定延迟倍数)默认为0,表示固定暂停1秒后进行重试。

依赖包:

        <dependency>
            <groupId>org.springframework.retry</groupId>
            <artifactId>spring-retry</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

添加 @EnableRetry 注解

@SpringBootApplication(scanBasePackages = {"com.example.demo"})
@EnableRetry
public class DemoApplication {

}

使用示例:

controller

    @Autowired
    private RetryService retryService;
    @RequestMapping("testsz")
    public RestResultDTO getStudentInfo() throws Exception {
        retryService.doSomething();
        return RestResultDTO.ok();
    }

service


public  interface RetryService {
    public void doSomething();

}

impl


import com.axa.dataservice.backend.service.RetryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class RetryServiceImpl implements RetryService{

    @Retryable(value = Exception.class,maxAttempts = 3,backoff = @Backoff(delay = 3000,multiplier = 1.5))
    public void doSomething() {
        log.info("doSomething start.");
        int result = 1/0;
        log.info("doSomething end.");
    }


    /**
     * @Recover 的返回类型,必须跟 @Retryable修饰的方法返回值一致。否则不生效。
     *
     */
    @Recover
    public void recover(Exception e) {
        log.info("retry failed recover");
        log.info("retry Exception:"+e);
        //是否需要入库记录
    }

}

执行结果:

可以看到,@Retryable 修饰的方法执行了3次。仍旧失败后,会执行 @Recover 修饰的方法。

在这里插入图片描述

也可以使用下面发生执行异常重试

@Slf4j
@Component
@EnableRetry
public class RecoryTest {
    
    @Retryable(value = {RetryException.class}, // 指定发生的异常进行重试
            maxAttempts=5,                     // 重试次数, 默认即为3
            backoff = @Backoff(delay = 2000L, multiplier = 2)) // 每次重试延迟毫秒数 及 延迟倍数
    @Async
    public void retry() {
        log.info("retry start");
        throw new RetryException("retry fail");
    }
 
    @Recover
    public void recover (RetryException e) {
        log.error("recovery,{}",e.getMessage());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值