繁体   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