このバージョンはまだ開発中であり、まだ安定しているとは見なされていません。最新の安定バージョンについては、Spring Cloud Commons 4.3.0 を使用してください!

Spring Cloud Circuit Breaker

Spring Cloud サーキットブレーカーは、さまざまなサーキットブレーカー実装にわたる抽象化を提供します。アプリケーションで使用する一貫した API が提供されるため、開発者はアプリケーションのニーズに最適なサーキットブレーカーの実装を選択できます。

サポートされている実装

Spring Cloud は、次のサーキットブレーカーの実装をサポートしています。

コアコンセプト

コード内にサーキットブレーカーを作成するには、CircuitBreakerFactory API を使用できます。Spring Cloud Circuit Breaker スターターをクラスパスに含めると、この 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 が渡されます。フォールバックを提供したくない場合は、オプションでフォールバックを除外できます。

リアクティブコードのサーキットブレーカー

プロジェクト 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 をプロファイリングできます。フォールバック Function は、サーキットブレーカーが作動し、障害の原因となった Throwable が渡された場合に呼び出されます。

構成

型 Customizer の Bean を作成することで、サーキットブレーカーを構成できます。Customizer インターフェースには、Object を使用してカスタマイズする単一のメソッド ( customize と呼ばれる) があります。

特定の実装をカスタマイズする方法の詳細については、次のドキュメントを参照してください。

Resilience4JCircuitBreaker などの一部の CircuitBreaker 実装は、CircuitBreaker#run が呼び出されるたびに customize メソッドを呼び出します。非効率的になる可能性があります。その場合は、CircuitBreaker#once メソッドを使用できます。これは、たとえば、Resilience4j のイベントを使用する (英語) 場合など、customize を何度も呼び出すことが意味がない場合に役立ちます。

次の例は、各 io.github.resilience4j.circuitbreaker.CircuitBreaker がイベントを消費する方法を示しています。

Customizer.once(circuitBreaker -> {
  circuitBreaker.getEventPublisher()
    .onStateTransition(event -> log.info("{}: {}", event.getCircuitBreakerName(), event.getStateTransition()));
}, CircuitBreaker::getName)

Spring HTTP サービスクライアントサポート

Spring Cloud provides support for Spring HTTP Service Clients integration through the following configurers:

  • CircuitBreakerRestClientHttpServiceGroupConfigurer

  • CircuitBreakerWebClientHttpServiceGroupConfigurer

これらのコンフィギュレータは、Spring HTTP Service Client Groups の CircuitBreaker サポートを有効にします。

フォールバッククラスが @HttpServiceFallbackAnnotation を使用して構成されている場合、CircuitBreaker アダプターデコレータが追加されます: - CircuitBreakerAdapterDecorator は RestClient とともに使用されます - ReactiveCircuitBreakerAdapterDecorator は WebClient とともに使用されます

適切なプロパティを設定することで、HTTP サービスクライアントの CircuitBreaker 統合を無効にすることができます。

  • ブロッキング(RestClient)クライアントの場合: spring.cloud.circuitbreaker.http-services.enabled=false

  • For reactive (WebClient) clients: spring.cloud.circuitbreaker.reactive-http-services.enabled=false

This prevents CircuitBreaker decorators from being applied to interface-based HTTP client groups.

Declaring Fallbacks with Annotations

Fallbacks are configured using the @HttpServiceFallback annotation on configuration classes. This annotation allows you to declare:

  • The fallback implementation class (via value)

  • The service interfaces the fallback supports (via forService, optional)

  • The group the fallback applies to (via forGroup, optional)

Multiple @HttpServiceFallback annotations can be declared on the same class using Java ’ s @Repeatable annotation mechanism. If no group is specified, the fallback applies to all groups that do not have an explicit per-group fallback for the given service interfaces.

Fallback classes are resolved using the following precedence:

  1. A fallback class with both matching forService and forGroup

  2. A fallback class with matching forService and no forGroup (global fallback for service)

  3. A fallback class with no forService or forGroup (default for all services in group or globally)

サンプル

@HttpServiceFallback(value = DefaultFallbacks.class)
@HttpServiceFallback(value = GroupAndServiceSpecificFallbacks.class, service = {BillingService.class, ShippingService.class}, group = "billing")
public class MyFallbackConfig {
    ...
}

This configuration results in:

  • DefaultFallbacks used as a global fallback for all services not explicitly handled

  • GroupAndServiceSpecificFallbacks used only for BillingService and ShippingService within the "billing" group

  • The fallback class and its methods must be public

  • Fallback methods must not be annotated with @HttpExchange annotations

How CircuitBreaker Adapters Work

The adapters wrap @HttpExchange method calls with CircuitBreaker logic. When a fallback is triggered, a proxy is created using the user-defined fallback class. The appropriate fallback method is selected by matching:

  • A method with the same name and parameter types, or

  • A method with the same name and parameter types preceded by a Throwable argument (to access the cause of failure)

Given the following interface:

@HttpExchange("/test")
public interface TestService {

    @GetExchange("/{id}")
    Person test(@PathVariable UUID id);

    @GetExchange
    String test();
}

A matching fallback class could be:

public class TestServiceFallback {

    public Person test(UUID id);

    public String test(Throwable cause);
}