使用Spring Retry优雅的实现业务异常重试

在系统中经常遇到业务重试的逻辑,比如三方接口调用,timeout重试三遍,异常处理重试的兜底逻辑等。那你是不是还在用下面这种方式呢:
使用Spring Retry优雅的实现业务异常重试_第1张图片
我想大家可能很多时候也会这么写,这是能想到的第一个方法,但是我们这段代码,会觉得很别扭,不够优雅,如果有多个重试的逻辑,就会显得重复代码太多,也不容易理解,总之在遇到Spring Retry之前我也一直在想有没有更好的方法去解决这种问题。下面我们来看看Spring Retry如何实现的。

项目配置

添加依赖

    
        
            org.springframework.retry
            spring-retry
            1.3.1
        
    

启用Spring Retry支持,添加**@EnableRetry**注解

@SpringBootApplication
@EnableRetry
public class Launcher {
    public static void main(String[] args) {
        SpringApplication.run(Launcher.class, args);
    }
}

@Retryable 注解形式

注解方式就是在启用重试特性的方法上使用@Retryable注释。

public interface RetryService {
    /**
     * 指定异常CustomRetryException重试,重试最大次数为4(默认是3),重试补偿机制间隔200毫秒
     * 还可以配置exclude,指定异常不充实,默认为空
     * @return result
     * @throws CustomRetryException 指定异常
     */
    @Retryable(value = {CustomRetryException.class},maxAttempts = 4,backoff = @Backoff(200))
    String retry() throws CustomRetryException;
}
  • value属性告诉 Spring retry 在方法在CustomRetryException异常出现时触发重试。
  • maxAttempts设置重试的最大次数,如果没有指定默认值为3。
  • backoff指定下次重试的延迟时间,默认值为1秒。

@Recover注解使用
当被@Retryable注解的方法由于指定的异常而失败时,用于定义单独恢复方法的@Recover注释。

@Service
@Slf4j
public class RetryServiceImpl implements RetryService {private static int count = 1;@Override
    public String retry() throws CustomRetryException {
        log.info("retry{},throw CustomRetryException in method retry",count);
        count ++;
        throw new CustomRetryException("throw custom exception");
    }@Recover
    public String recover(Throwable throwable) {
        log.info("Default Retry service test");
        return "Error Class :: " + throwable.getClass().getName();
    }}

RetryTemplate实现形式

@Bean
    @ConditionalOnMissingBean
    public RetryTemplate retryTemplate(){
        final SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy();
        simpleRetryPolicy.setMaxAttempts(4);final FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
        fixedBackOffPolicy.setBackOffPeriod(1000L);return RetryTemplate.builder()
            .customPolicy(simpleRetryPolicy)
            .customBackoff(fixedBackOffPolicy)
            .retryOn(CustomRetryException.class)
            .build();
    }

// 执行部分
@Autowired
RetryTemplate retryTemplate;

template.execute(ctx -> {
    return backendAdapter.getBackendResponse(...);
});

总结

那么哪些地方我们能用到Spring Retry呢?有这两点建议

  • 仅在临时错误上使用重试。不建议它在永久错误中使用它,因为这样可能导致系统性能问题。
  • 它不是熔断器的替代的一种方式,最好在允许的情况下,既使用熔断器,又使用重试器。

你可能感兴趣的:(Java,spring,java,后端)