Specific Circuit Breaker Configuration

与提供默认配置类似,您可以创建一个 Customizer Bean,该 Bean 传递给 Resilience4JCircuitBreakerFactoryReactiveResilience4JCircuitBreakerFactory

@Bean
public Customizer<Resilience4JCircuitBreakerFactory> slowCustomizer() {
	return factory -> factory.configure(builder -> builder.circuitBreakerConfig(CircuitBreakerConfig.ofDefaults())
			.timeLimiterConfig(TimeLimiterConfig.custom().timeoutDuration(Duration.ofSeconds(2)).build()), "slow");
}

除了配置创建的断路器之外,您还可以自定义断路器在创建后且返回给调用者之前。为此,您可以使用 addCircuitBreakerCustomizer 方法。这对于向 Resilience4J 断路器添加事件处理程序非常有用。

@Bean
public Customizer<Resilience4JCircuitBreakerFactory> slowCustomizer() {
	return factory -> factory.addCircuitBreakerCustomizer(circuitBreaker -> circuitBreaker.getEventPublisher()
	.onError(normalFluxErrorConsumer).onSuccess(normalFluxSuccessConsumer), "normalflux");
}

如果您需要将安全上下文传播到断路器,则必须将断路器配置为使用 DelegatingSecurityContextExecutorService

@Bean
public Customizer<Resilience4JCircuitBreakerFactory> groupExecutorServiceCustomizer() {
	return factory -> factory.configureGroupExecutorService(group -> new DelegatingSecurityContextExecutorService(Executors.newVirtualThreadPerTaskExecutor()));
}

Reactive Example

@Bean
public Customizer<ReactiveResilience4JCircuitBreakerFactory> slowCustomizer() {
	return factory -> {
		factory.configure(builder -> builder
		.timeLimiterConfig(TimeLimiterConfig.custom().timeoutDuration(Duration.ofSeconds(2)).build())
		.circuitBreakerConfig(CircuitBreakerConfig.ofDefaults()), "slow", "slowflux");
		factory.addCircuitBreakerCustomizer(circuitBreaker -> circuitBreaker.getEventPublisher()
        	.onError(normalFluxErrorConsumer).onSuccess(normalFluxSuccessConsumer), "normalflux");
     };
}