[英]How to inject config properties in Spring Boot to Spring Retry annotation?
在spring啟動應用程序中,我在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.maxAttempts
和my.app.backOffdelay
的值注入Spring Retry注釋? 在下面的示例中,我想將maxAttempts的值10
和500L
的退避值替換為配置屬性的相應引用。
@Retryable(maxAttempts=10, include=TimeoutException.class, backoff=@Backoff(value = 500L))
從spring-retry-1.2.0開始,我們可以在@Retryable注釋中使用可配置屬性。
使用“maxAttemptsExpression”,請參閱以下代碼以了解用法,
@Retryable(maxAttemptsExpression = "#{${my.app.maxAttempts}}",
backoff = @Backoff(delayExpression = "#{${my.app. backOffDelay}}"))
如果使用任何小於1.2.0的版本,它將無法工作。此外,您不需要任何可配置的屬性類。
您還可以在表達式屬性中使用現有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);
哪里
retryProperties
是你的bean,它保存與你的情況相關的重試相關屬性。
您可以使用如下所示的Spring EL來加載屬性:
@Retryable(maxAttempts="${my.app.maxAttempts}",
include=TimeoutException.class,
backoff=@Backoff(value ="${my.app.backOffDelay}"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.