此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 spring-cloud-CircuitBreaker 3.1.3spring-doc.cn

特定断路器配置

与提供默认配置类似,您可以创建一个 bean,该 bean 将传递 或 。CustomizerResilience4JCircuitBreakerFactoryReactiveResilience4JCircuitBreakerFactoryspring-doc.cn

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

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

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

如果需要将安全上下文传播给 Circuit Breaker,则必须将 Circuit Breaker 配置为使用 。DelegatingSecurityContextExecutorServicespring-doc.cn

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

反应式示例

@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");
     };
}