栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring Retry教程(2)-注解方式的实现

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring Retry教程(2)-注解方式的实现

1. 在pom.xml中添加依赖

    org.springframework.retry
    spring-retry
    1.2.5.RELEASE



    org.springframework
    spring-aspects
    5.2.8.RELEASE

2. 在@Configuration类或者启动类中添加注释@EnableRetry
@Configuration
@EnableRetry
public class AppConfig { ... }

或

@SpringBootApplication
@EnableRetry
public class Application
3. 在需要重试的方法上添加注解@Retryable,@Recover来开启重试失败后调用的方法 3.1 @Retryable 作用于需要进行重试的方法
  • value:指定处理的异常类,默认为空
  • include:指定处理的异常类,默认为空,当include和exclude为空时,默认所有异常
  • exclude:指定哪些异常不处理,默认空
  • maxAttempts:最大重试次数。默认3次
3.2 @Backoff 作用于backoff中的补偿策略

补偿策略处理的是两次重试之间的时间间隔问题。

  • delay:指定等待时间,没有设置的话默认为1000ms
  • maxDelay:最大重试时间,没有设置默认为3000ms
  • multiplier:下一次调用时间的乘数
  • random:随机等待时间,默认值为false
@Service
public class SpringRetryService{
    private static final Logger LOGGER = LoggerFactory.getLogger(SpringRetryService.class);

    @Retryable(value = {Exception.class},exclude={}, maxAttempts = 5, backoff =@Backoff(value = 1000,multiplier = 2))
    public void testRetry() throws Exception {
        boolean result = false;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            LOGGER.info("重试方法被调用,当前时间是" + sdf.format(new Date()));
            int i = 9 / 0;
        } catch (Exception e) {
            throw new Exception("重试之后,还是失败了!", e);
        }
    }
    @Recover
    public void testRecovery(Exception e) {
        
        LOGGER.warn("重试5次依旧失败了!"+e.getMessage());
    }
}
4. Controller中测试
@RestController
@RequestMapping("/springRetry")
public class SpringRetryController {
    private static final Logger LOG = LoggerFactory.getLogger(SpringRetryController.class);
    @Autowired
    private SpringRetryService pringRetryService;
    @RequestMapping("/testSpringRetry")
    public String testSpringRetry() {
        LOG.info("invoke method testSpringRetry! ");
        try {
            pringRetryService.testRetry();
        } catch (Exception e) {
            LOG.error("重试失败了", e);
        }
        return " retry success";
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1020936.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号