我想創建一個@Bean第三方服務,如 Keycloak(或任何其他),在任何給定時間可能無法訪問。此物件應重試結果Keycloakbean 的所有方法。
我嘗試了以下方法:
@Configuration
@EnableRetry
class KeycloakBeanProvider() {
@Bean
@Retryable
fun keycloak(oauth2ClientRegistration: ClientRegistration): Keycloak {
return KeycloakBuilder.builder()
.serverUrl(serverUrl)
.realm(oauth2ClientRegistration.clientName)
.grantType(OAuth2Constants.CLIENT_CREDENTIALS)
.clientId(oauth2ClientRegistration.clientId)
.clientSecret(oauth2ClientRegistration.clientSecret)
.build()
}
}
但是這種方式只會重試 bean 的創建,而不是對 bean 的實際方法呼叫。我知道@Retryable可以在班級級別使用,但我不擁有該Keycloak班級,因此無法將其添加到那里。
如何使生成的Keycloakbean的方法可重試?
uj5u.com熱心網友回復:
你必須注釋Keycloak帶@Retryable。
@SpringBootApplication
@EnableRetry
public class So70593939Application {
public static void main(String[] args) {
SpringApplication.run(So70593939Application.class, args);
}
@Bean
ApplicationRunner runner(Foo foo) {
return args -> {
foo.foo("called foo");
foo.bar("called bar");
};
}
}
@Component
@Retryable
class Foo {
public void foo(String in) {
System.out.println("foo");
throw new RuntimeException("test");
}
public void bar(String in) {
System.out.println("bar");
throw new RuntimeException("test");
}
@Recover
public void recover(Exception ex, String in) {
System.out.println(ex.getMessage() ":" in);
}
}
foo
foo
foo
test:called foo
bar
bar
bar
test:called bar
如果您不能對類進行注釋(例如,因為它來自另一個專案),則需要使用 aRetryTemplate來呼叫其方法,而不是使用基于注釋的重試。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/404718.html
標籤:
上一篇:無法在use{}塊內迭代流
