SpringBoot集成retry(7)

一.概述

二.快速入门

1.导依赖

        <!--retry的依赖-->
        <dependency>
            <groupId>org.springframework.retry</groupId>
            <artifactId>spring-retry</artifactId>
            <version>1.3.2</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
        </dependency>

2.在启动类上加@EnableRetry注解

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

@EnableRetry//加上这个注解
@SpringBootApplication(scanBasePackages="com.guguo")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}

3.测试代码

package com.guguo.controller;

import io.swagger.annotations.Api;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.retry.RetryException;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;



@Slf4j
@RestController
@RequestMapping("")
@Api(tags = "测试重试")
public class RetryController {

    /**
     * @Retryable 参数说明
     * value:抛出指定异常才会重试
     * maxAttempts:最大重试次数,默认3次
     * backoff:重试等待策略
     * recover:执行回调方法名称
     */
    @GetMapping("retryable")
    @SneakyThrows(Exception.class)
    @Retryable(value = RetryException.class, maxAttempts = 2,
            backoff = @Backoff(delay = 1000, multiplier = 2), recover = "recover")//第一次等1秒,第二次等2秒,第三次等4秒
    public String retry(@RequestParam String msg) {
        if (4 % 3 == 0) {
            return "OK";
        }
        log.info("服务调用不正常。。。");
        throw new RetryException("服务调用不正常。。。");
    }

    @Recover//作为恢复处理程序的方法调用的注释。
    // 重试方法最终会调用标注了@Recover 的方法;需要注意的是发生的异常和入参类型一致时才会回调。
    //比如,在上面的方法中有个String类型的参数,那么回调函数中也要有个String类型的参数,参数名相不相同无所谓
    public String recover(RetryException e, String message) {
        log.info("执行回调方法: {}", message);
        System.out.println("我是回调函数");
        return "fail";
    }

}

4.结果

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值