20

在 Spring Boot 应用程序中,我在 yaml 文件中定义了一些配置属性,如下所示。

my.app.maxAttempts = 10
my.app.backOffDelay = 500L

还有一个示例 bean

@ConfigurationProperties(prefix = "my.app")
public class ConfigProperties {
  private int maxAttempts;
  private long backOffDelay;

  public int getMaxAttempts() {
    return maxAttempts;
  }

  public void setMaxAttempts(int maxAttempts) {
    this.maxAttempts = maxAttempts;
  }

  public void setBackOffDelay(long backOffDelay) {
    this.backOffDelay = backOffDelay;
  }

  public long getBackOffDelay() {
    return backOffDelay;
  }

如何将值注入my.app.maxAttemptsSpring my.app.backOffdelayRetry 注释?在下面的示例中,我想将10maxAttempts 和500Lbackoff 值的值替换为配置属性的相应引用。

@Retryable(maxAttempts=10, include=TimeoutException.class, backoff=@Backoff(value = 500L))
4

3 回答 3

27

spring-retry-1.2.0开始,我们可以在 @Retryable 注解中使用可配置的属性。

使用“maxAttemptsExpression”,参考下面的代码使用,

 @Retryable(maxAttemptsExpression = "#{${my.app.maxAttempts}}",
 backoff = @Backoff(delayExpression = "#{${my.app. backOffDelay}}"))

如果您使用低于 1.2.0 的任何版本,它将不起作用。此外,您不需要任何可配置的属性类。

于 2017-03-31T15:09:44.323 回答
12

您还可以在表达式属性中使用现有的 bean。

    @Retryable(include = RuntimeException.class,
           maxAttemptsExpression = "#{@retryProperties.getMaxAttempts()}",
           backoff = @Backoff(delayExpression = "#{@retryProperties.getBackOffInitialInterval()}",
                              maxDelayExpression = "#{@retryProperties.getBackOffMaxInterval" + "()}",
                              multiplierExpression = "#{@retryProperties.getBackOffIntervalMultiplier()}"))
    String perform();

    @Recover
    String recover(RuntimeException exception);

在哪里

重试属性

是您的 bean,它在您的情况下拥有与重试相关的属性。

于 2017-04-13T14:11:49.747 回答
0

您可以使用如下所示的 Spring EL 来加载属性:

@Retryable(maxAttempts="${my.app.maxAttempts}", 
  include=TimeoutException.class, 
  backoff=@Backoff(value ="${my.app.backOffDelay}"))
于 2017-03-31T15:02:32.880 回答