SpringBoot技术实践-SpringRetry重试框架,查缺补漏

本文介绍了SpringBoot中SpringRetry的使用,通过@Controller和@Retryable注解展示了如何实现接口重试,详细配置了初始延迟和重试次数。文章末尾作者分享了帮助求职者节省时间的心得,并提供了相关的学习资源。
摘要由CSDN通过智能技术生成
}

}




1.  在controller中注入RetryTemplate使用,也可以是在service中



@RestController

public class SpringRetryController {

@Resource

private RetryTemplate retryTemplate;

private static int count = 0;



@RequestMapping("/retry")

public Object retry() {

    try {

        count = 0;

        retryTemplate.execute((RetryCallback<Void, RuntimeException>) context -> {

            // 业务代码

            // ....

            // 模拟抛出异常

            ++count;

            throw new RuntimeException("抛出异常");

        });

    } catch (RuntimeException e) {

        System.out.println("Exception");

    }



    return "retry = " + count;

}

}




1.  访问retry接口,然后观察日志输出



18:27:20.648 - http-nio-8888-exec-1 - open

18:27:20.649 - http-nio-8888-exec-1 - retryTemplate.execute执行

18:27:20.649 - http-nio-8888-exec-1 - onError

18:27:21.658 - http-nio-8888-exec-1 - retryTemplate.execute执行

18:27:21.658 - http-nio-8888-exec-1 - onError

18:27:23.670 - http-nio-8888-exec-1 - retryTemplate.execute执行

18:27:23.670 - http-nio-8888-exec-1 - onError

18:27:27.679 - http-nio-8888-exec-1 - retryTemplate.execute执行

18:27:27.679 - http-nio-8888-exec-1 - onError

18:27:35.681 - http-nio-8888-exec-1 - retryTemplate.execute执行

18:27:35.681 - http-nio-8888-exec-1 - onError

18:27:35.681 - http-nio-8888-exec-1 - close




[](https://gitee.com/vip204888/java-p7)三、EnableRetry

================================================================================



1.  @EnableRetry开启重试,在类上指定的时候方法将默认执行,重试三次

2.  定义service,开启@EnableRetry注解和指定@Retryable,重试可以参考后面一节



import org.springframework.retry.annotation.Retryable;

public interface RetryService {

/**

 * 重试方法调用

 */

@Retryable

void retryServiceCall();

}


import org.springframework.retry.annotation.EnableRetry;

import org.springframework.stereotype.Service;



@EnableRetry

@Service

public class RetryServiceImpl implements RetryService {



    @Override

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值