Specific Circuit Breaker Configuration
与提供默认配置类似,您可以创建一个 Customizer
Bean,该 Bean 传递给 Resilience4JCircuitBreakerFactory
或 ReactiveResilience4JCircuitBreakerFactory
。
Similarly to providing a default configuration, you can create a Customizer
bean this is passed a
Resilience4JCircuitBreakerFactory
or ReactiveResilience4JCircuitBreakerFactory
.
@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 断路器添加事件处理程序非常有用。
In addition to configuring the circuit breaker that is created you can also customize the circuit breaker after it has been created but before it is returned to the caller.
To do this you can use the addCircuitBreakerCustomizer
method.
This can be useful for adding event handlers to Resilience4J circuit breakers.
@Bean
public Customizer<Resilience4JCircuitBreakerFactory> slowCustomizer() {
return factory -> factory.addCircuitBreakerCustomizer(circuitBreaker -> circuitBreaker.getEventPublisher()
.onError(normalFluxErrorConsumer).onSuccess(normalFluxSuccessConsumer), "normalflux");
}
如果您需要将安全上下文传播到断路器,则必须将断路器配置为使用 DelegatingSecurityContextExecutorService
。
If you need to propogate the security context to the Circuit Breaker you must configure the circuit breaker to use 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");
};
}