springboot重试(@Retryable)

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

<dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
package org.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.retry.annotation.EnableRetry;

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@EnableRetry
public class RetryApplication {

    public static void main(String[] args) {
        SpringApplication.run(RetryApplication.class, args);
    }

}

 

package org.example.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.example.service.RetryService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

@Service
@Slf4j
public class RetryServiceImpl implements RetryService {

    /**
     * interceptor:可以通过该参数,指定方法拦截器的bean名称
     * value:抛出指定异常才会重试
     * include:和value一样,默认为空,当exclude也为空时,默认所以异常
     * exclude:指定不处理的异常
     * maxAttempts:最大重试次数,默认3次
     * backoff:重试等待策略,默认使用@Backoff,@Backoff的value默认为1000L,我们设置为2000L;multiplier(指定延迟倍数)默认为0,表示固定暂停1秒后进行重试,如果把multiplier设置为1.5,则第一次重试为2秒,第二次为3秒,第三次为4.5秒。
     * @return  "${sobot.url}"
     */
    @Override
    @Retryable(value = Exception.class, maxAttemptsExpression ="${retry.maxAttempts}" , backoff = @Backoff(delayExpression = "${retry.delay}", multiplierExpression = "${retry.multiplier}"))
    public String retry() {
        log.info("retry............"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        int i=10/0;
        return "hello";
    }

    @Recover
    public String doRecover(Throwable throwable){
        log.info("the message:{}",throwable.getMessage());
        return "出现异常了";
    }

    //若retry里面有调用请求,recover里面不要嵌套调用retry,会出现http请求连接数达到上限,出现无法调用的情况
    @Recover
    public String doRecover(Throwable throwable,boolean ifFlag){
        log.info("the message:{},flag:{}",throwable.getMessage(),ifFlag);
        return "出现异常了";
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值