# 重试机制 **Repository Path**: vespt/retry-mechanism ## Basic Information - **Project Name**: 重试机制 - **Description**: No description available - **Primary Language**: Java - **License**: AFL-3.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 0 - **Created**: 2023-11-15 - **Last Updated**: 2023-12-24 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # 重试机制 1. 添加依赖 org.springframework.retry spring-retry org.springframework.boot spring-boot-starter-aop 2.主程序加入注解@EnableRetry @EnableRetry @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } 3. 代理在另一个类中使用注解 @Retryable(value = Exception.class,maxAttempts = 10,backoff = @Backoff(delay = 300,multiplier = 1.5)) 4.如果要后续处理,加上相同返回值的 @Recover 注解,相应代码如下: /** * * value:抛出指定异常才会重试 * exclude:指定不处理的异常 * maxAttempts:最大重试次数,默认3次 * backoff:重试等待策略,默认使用@Backoff, * @Backoff的value(相当于delay)表示隔多少毫秒后重试,默认为1000L; * multiplier(指定延迟倍数)默认为0,表示固定暂停1秒后进行重试。 * ———————————————— * 版权声明:本文为CSDN博主「乐之者v」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 * 原文链接:https://blog.csdn.net/sinat_32502451/article/details/133774582 * */ @Service public class ServiceImpl implements IService { @Retryable(value = RuntimeException.class,maxAttempts = 10,backoff = @Backoff(delay = 300,multiplier = 1.5)) @Override public String getData(){ System.out.println(("开始执行---------"+System.currentTimeMillis()+"_"+Thread.currentThread().getName())); try { int i =1/0 ; } catch (Exception e) { // e.printStackTrace(); throw new RuntimeException("异常····"); } System.out.println("执行完毕"); return "" ; } //和上述方法返回值相同的情况下,可以实现重试失败的后续处理,比如存库等 // @Recover // public String recover(Exception e) { // System.out.println(("retry failed recover")); // System.out.println(("retry Exception:"+e)); // //是否需要入库记录 // return null; // }