spring Retry 重试机制

		<!-- 重试机制 -->
        <dependency>
            <groupId>org.springframework.retry</groupId>
            <artifactId>spring-retry</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
 /**
     * value:抛出指定异常才会重试
     * include:和value一样,默认为空,当exclude也为空时,默认所有异常
     * exclude:指定不处理的异常
     * maxAttempts:最大重试次数,默认3次
     * backoff:重试等待策略,
     * 默认使用@Backoff,@Backoff的value默认为1000L,我们设置为2000; 以毫秒为单位的延迟(默认 1000)
     * multiplier(指定延迟倍数)默认为0,表示固定暂停1秒后进行重试,如果把multiplier设置为1.5,则第一次重试为2秒,第二次为 [1.5 * 2 = 3] 秒,第三次为 [ 3 * 1.5 = 4.5 ]秒。
     * @param code
     * @return
     * @throws Exception
     */
    @Retryable(value = Exception.class,maxAttempts = 3,backoff = @Backoff(delay = 2000,multiplier = 1.5),recover = "recover1")
    @RequestMapping("retryTest")
    public String retryTest(String code) {
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"  ,重试机制,"+code);
        if(true){
            throw  new RuntimeException();
        }
        return "1";
    }
    //Spring-Retry还提供了@Recover注解,用于@Retryable重试失败后处理方法。如果不需要回调方法,可以直接不写回调方法,那么实现的效果是,重试次数完了后,如果还是没成功没符合业务判断,就抛出异常。
	// @Recover 方法 注意:第一个参数为报错异常信息,其他参数与返回类型必须和要进行回调的方法一致,此处必须和retryTest方法的入参和返回值类型一致,如果有多个就通过 @Retryable 中的 recover =“xx” 指定好。
    @Recover
    public String recover(Exception e,String code)
    {
        System.out.println("重试次数耗尽,错误信息入库,进行后续补偿操作!");
        return "0";
    }

    @Recover
    public String recover1(Exception e,String code)
    {
        System.out.println("1重试次数耗尽,错误信息入库,进行后续补偿操作!");
        return "0";
    }

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值