領先一步
VMware 提供培訓和認證,助您加速進步。
瞭解更多Spring Cloud 斷路器為不同的斷路器實現提供了抽象。它提供了一致的 API 供您在應用程式中使用,讓開發人員可以選擇最適合其應用程式需求的斷路器實現。
要建立程式碼中的斷路器,您可以使用 CircuitBreakerFactory API。當您在類路徑中包含 Spring Cloud 斷路器啟動器時,會自動為您建立一個實現此 API 的 bean。下面給出了一個使用此 API 的非常簡單的示例
@Service
public static class DemoControllerService {
private RestTemplate rest;
private CircuitBreakerFactory cbFactory;
public DemoControllerService(RestTemplate rest, CircuitBreakerFactory cbFactory) {
this.rest = rest;
this.cbFactory = cbFactory;
}
public String slow() {
return cbFactory.create("slow").run(() -> rest.getForObject("/slow", String.class), throwable -> "fallback");
}
}
CircuitBreakerFactory.create API 將建立一個名為 CircuitBreaker 的類的例項。run 方法接受一個 Supplier 和一個 Function。Supplier 是您將包裝在斷路器中的程式碼。Function 是在斷路器跳閘時將執行的回退。該函式將傳遞導致回退觸發的 Throwable。如果不想提供回退,可以選擇排除回退。
如果 Project Reactor 位於類路徑中,那麼您也可以將 ReactiveCircuitBreakerFactory 用於您的響應式程式碼。
@Service
public static class DemoControllerService {
private ReactiveCircuitBreakerFactory cbFactory;
private WebClient webClient;
public DemoControllerService(WebClient webClient, ReactiveCircuitBreakerFactory cbFactory) {
this.webClient = webClient;
this.cbFactory = cbFactory;
}
public Mono<String> slow() {
return webClient.get().uri("/slow").retrieve().bodyToMono(String.class).transform(
it -> cbFactory.create("slow").run(it, throwable -> return Mono.just("fallback")));
}
}
ReactiveCircuitBreakerFactory.create API 將建立一個名為 ReactiveCircuitBreaker 的類的例項。run 方法接受一個 Mono 或 Flux 並將其包裝在斷路器中。您可以選擇提供一個回退 Function,該函式將在斷路器跳閘時被呼叫,並將傳遞導致失敗的 Throwable。
Spring Cloud BOM 提供了以下啟動器
Resilience4J - org.springframework.cloud:spring-cloud-starter-circuitbreaker-resilience4j
響應式 Resilience4J - org.springframework.cloud:spring-cloud-starter-circuitbreaker-reactor-resilience4j
Spring Retry - org.springframework.cloud:spring-cloud-starter-circuitbreaker-spring-retry