重试支持Spring Retry

引入maven依赖
<dependency>
    <groupId>org.springframework.retry</groupId>
    <artifactId>spring-retry</artifactId>
    <version>1.3.1.RELEASE</version>
</dependency>
添加@Retryable和@Recover注解
package com.test;

import org.springframework.remoting.RemoteAccessException;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

@Service
public class TestService {

    @Retryable(value= {Exception.class},
    maxAttempts = 3,
    backoff = @Backoff(delay = 5000l,multiplier = 1))
    public void something() throws Exception {
        System.out.println("do something...");
        throw new Exception("调用异常");
    }

    @Recover
    public void recover(Exception e) {
        System.out.println(e.getMessage());
    }

}
  • @Retryable注解
    被注解的方法发生异常时会重试
    value:指定发生的异常进行重试
    include:和value一样,默认空,当exclude也为空时,所有异常都重试
    exclude:指定异常不重试,默认空,当include也为空时,所有异常都重试
    maxAttemps:重试次数,默认3
    backoff:重试补偿机制,默认没有
  • @Backoff注解
    delay:指定延迟后重试
    multiplier:指定延迟的倍数,比如delay=5000l,multiplier=2时,第一次重试为5秒后,第二次为10秒,第三次为20秒
  • @Recover
    当重试到达指定次数时,被注解的方法将被回调,可以在该方法中进行日志处理。需要注意的是发生的异常和入参类型一致时才会回调
SpringBoot启动测试
package com.test;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.retry.annotation.EnableRetry;

@SpringBootApplication
@EnableRetry
public class TestApplication {
    
    @Autowired
    private TestService testService;
    
    @RequestMapping("/test")
    public String test() {
        testService.something();
        return "200";
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(TestApplication.class, args);
    }
    
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容