Spring Cloud Retry 指南 | baeldung


Spring Retry 提供了自动重新调用失败操作的能力。这在错误可能是暂时的(如瞬时网络故障)时很有用。
在本教程中,我们将看到使用Spring Retry 的各种方式:注释、RetryTemplate 和回调。

让我们首先将spring-retry依赖项添加到我们的pom.xml文件中:

<dependency>
    <groupId>org.springframework.retry</groupId>
    <artifactId>spring-retry</artifactId>
    <version>1.2.5.RELEASE</version>
</dependency>

我们还需要将 Spring AOP 添加到我们的项目中:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>5.2.8.RELEASE</version>
</dependency>

查看 Maven Central 以获得最新版本的spring-retry和spring-aspects依赖项。

要在应用程序中启用 Spring Retry,我们需要将@EnableRetry注释添加到我们的@Configuration类:

@Configuration
@EnableRetry
public class AppConfig { ... }


我们可以使用@Retryable注释为方法添加重试功能:

@Service

public interface MyService { 

    @Retryable(value = RuntimeException.class
    void retryService(String sql); 
}

这里,在抛出RuntimeException时尝试重试。
根据@Retryable的默认行为,重试最多可能发生 3 次,两次重试之间有 1 秒的延迟。

使用@Recover注释添加一个恢复方法:

@Service
public interface MyService { 

    @Retryable(value = SQLException.class)
    void retryServiceWithRecovery(String sql) throws SQLException; 

    @Recover
    void recover(SQLException e, String sql); 
}

这里,在抛出SQLException时尝试重试。 当@Retryable方法因指定异常而失败时, @Recover注释定义了一个单独的恢复方法。
因此,如果retryServiceWithRecovery方法在三次尝试后仍然抛出SqlException,则将调用recover()方法。
恢复处理程序应该具有Throwable类型的第一个参数(可选)和相同的返回类型。 以下参数以相同顺序从失败方法的参数列表中填充。

高级
为了自定义重试的行为,我们可以使用参数maxAttempts和backoff:

@Service
public interface MyService {

    @Retryable(value = SQLException.class, maxAttempts = 2, backoff = @Backoff(delay = 100))
    void retryServiceWithCustomization(String sql) throws SQLException;
}

最多将有两次尝试和 100 毫秒的延迟。

我们还可以在@Retryable注解中使用属性。

为了演示这一点,我们将了解如何将delay和maxAttempts的值外部化 到属性文件中。

首先,让我们在名为 retryConfig 的文件中定义属性。属性:

retry.maxAttempts=2
retry.maxDelay=100

然后我们指示我们的@Configuration类加载这个文件:

// ...
@PropertySource(
"classpath:retryConfig.properties")
public class AppConfig { ... }

最后,我们可以 在@Retryable定义中注入retry.maxAttempts和retry.maxDelay的值:

@Service 
public interface MyService {

    @Retryable(value = SQLException.class, maxAttemptsExpression = "${retry.maxAttempts}",
               backoff = @Backoff(delayExpression =
"${retry.maxDelay}")) 
    void retryServiceWithExternalConfiguration(String sql) throws SQLException; 
}

请注意,我们现在使用maxAttemptsExpression和delayExpression而不是maxAttempts和delay。

重试模板等高级点击标题

这些示例的源代码可在 GitHub 上找到。