簡體   English   中英

如何在普通 Java 中為 Resilience4j 2.0 斷路器定義回退方法?

[英]How do I define fallback method for Resilience4j 2.0 Circuit Breaker in a plain Java?

如何在普通 Java 中為 Resillience4j 2.0 斷路器定義回退方法?

我在官方文檔和 API 中都找不到示例。

我有一個非常簡單的代碼,我想在原始方法失敗時注冊一個回退/恢復方法。

WeatherApi weatherApi = new FaultyWeatherService();

CircuitBreakerRegistry registry = CircuitBreakerRegistry.of(
    CircuitBreakerConfig.custom()
        .failureRateThreshold(1)
        .minimumNumberOfCalls(1)
        .build()
);

CircuitBreaker breaker = registry.circuitBreaker("weather-service");

Function<String, String> weatherFunction = CircuitBreaker
    .decorateFunction(breaker, weatherApi::getWeatherFor);

for (int i = 0; i < 10; i++) {
    try {
        System.out.println(weatherFunction.apply("krakow"));
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

您可以在CircuitBreaker object 上使用withFallback方法。以下是如何在代碼中使用它的示例:

// Define your fallback method
Function<String, String> fallback = (city) -> {
  // Return a default value or do some other recovery logic here
  return "Unknown";
};


// Use the withFallback method to register the fallback
Function<String, String> weatherFunction = CircuitBreaker
    .decorateFunction(breaker, weatherApi::getWeatherFor)
    .withFallback(fallback);

withFallback方法采用Function object 將在原始 function(在本例中為weatherApi::getWeatherFor )拋出異常時調用。 此 function 應返回與原始 function 相同的類型(在本例中為String )。

您還可以使用以Class object 作為參數的withFallback方法為每種異常類型指定不同的回退。 這允許您以不同的方式處理不同的異常。 例如:

// Define your fallback methods
Function<String, String> ioExceptionFallback = (city) -> {
  // Return a default value or do some other recovery logic here
  return "Unknown";
};

Function<String, String> runtimeExceptionFallback = (city) -> {
  // Return a default value or do some other recovery logic here
  return "Unavailable";
};

// Use the withFallback methods to register the fallbacks
Function<String, String> weatherFunction = CircuitBreaker
    .decorateFunction(breaker, weatherApi::getWeatherFor)
    .withFallback(IOException.class, ioExceptionFallback)
    .withFallback(RuntimeException.class, runtimeExceptionFallback);

在此示例中,如果weatherApi::getWeatherFor ioExceptionFallback拋出IOException ,將調用runtimeExceptionFallback function ,如果拋出任何其他RuntimeException ,將調用 runtimeExceptionFallback function 。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM