io.github.resilience4j.circuitbreaker.CircuitBreakerConfig Java Examples

The following examples show how to use io.github.resilience4j.circuitbreaker.CircuitBreakerConfig. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CircuitBreakerAutoTransitionStateMachineTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()
        .failureRateThreshold(50)
        .slidingWindow(5, 5, CircuitBreakerConfig.SlidingWindowType.COUNT_BASED)
        .permittedNumberOfCallsInHalfOpenState(3)
        .automaticTransitionFromOpenToHalfOpenEnabled(true)
        .waitDurationInOpenState(Duration.ofSeconds(2))
        .recordException(error -> !(error instanceof NumberFormatException))
        .build();

    SchedulerFactory schedulerFactoryMock = mock(SchedulerFactory.class);
    schedulerMock = mock(ScheduledExecutorService.class);
    when(schedulerFactoryMock.getScheduler()).thenReturn(schedulerMock);
    circuitBreaker = new CircuitBreakerStateMachine("testName", circuitBreakerConfig,
        schedulerFactoryMock);
}
 
Example #2
Source File: SpringApp.java    From tutorials with MIT License 6 votes vote down vote up
@Bean
public Customizer<Resilience4JCircuitBreakerFactory> globalCustomConfiguration() {
    TimeLimiterConfig timeLimiterConfig = TimeLimiterConfig.custom()
            .timeoutDuration(Duration.ofSeconds(4))
            .build();
    CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()
            .failureRateThreshold(50)
            .waitDurationInOpenState(Duration.ofMillis(1000))
            .slidingWindowSize(2)
            .build();

    return factory -> factory.configureDefault(id -> new Resilience4JConfigBuilder(id)
            .timeLimiterConfig(timeLimiterConfig)
            .circuitBreakerConfig(circuitBreakerConfig)
            .build());
}
 
Example #3
Source File: CircuitBreakersHealthIndicator.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
private static Health.Builder addDetails(Health.Builder builder,
                                         CircuitBreaker circuitBreaker) {
    CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
    CircuitBreakerConfig config = circuitBreaker.getCircuitBreakerConfig();
    builder.withDetail(FAILURE_RATE, metrics.getFailureRate() + "%")
        .withDetail(FAILURE_RATE_THRESHOLD, config.getFailureRateThreshold() + "%")
        .withDetail(SLOW_CALL_RATE, metrics.getSlowCallRate() + "%")
        .withDetail(SLOW_CALL_RATE_THRESHOLD, config.getSlowCallRateThreshold() + "%")
        .withDetail(BUFFERED_CALLS, metrics.getNumberOfBufferedCalls())
        .withDetail(SLOW_CALLS, metrics.getNumberOfSlowCalls())
        .withDetail(SLOW_FAILED_CALLS, metrics.getNumberOfSlowFailedCalls())
        .withDetail(FAILED_CALLS, metrics.getNumberOfFailedCalls())
        .withDetail(NOT_PERMITTED, metrics.getNumberOfNotPermittedCalls())
        .withDetail(STATE, circuitBreaker.getState());
    return builder;
}
 
Example #4
Source File: TaggedCircuitBreakerMetricsPublisherTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    meterRegistry = new SimpleMeterRegistry();
    taggedCircuitBreakerMetricsPublisher =
        new TaggedCircuitBreakerMetricsPublisher(meterRegistry);
    circuitBreakerRegistry =
        CircuitBreakerRegistry
            .of(CircuitBreakerConfig.ofDefaults(), taggedCircuitBreakerMetricsPublisher);

    CircuitBreakerConfig configWithSlowCallThreshold = CircuitBreakerConfig.custom()
        .slowCallDurationThreshold(Duration.ofSeconds(1)).build();
    circuitBreaker = circuitBreakerRegistry
        .circuitBreaker("backendA", configWithSlowCallThreshold);
    // record some basic stats
    circuitBreaker.onSuccess(0, TimeUnit.NANOSECONDS);
    circuitBreaker.onError(0, TimeUnit.NANOSECONDS, new RuntimeException("oops"));
    // record slow call
    circuitBreaker.onSuccess(2000, TimeUnit.NANOSECONDS);
    circuitBreaker.onError(2000, TimeUnit.NANOSECONDS, new RuntimeException("oops"));

}
 
Example #5
Source File: StorageServiceSupport.java    From front50 with Apache License 2.0 6 votes vote down vote up
public T findById(String id) throws NotFoundException {
  CircuitBreaker breaker =
      circuitBreakerRegistry.circuitBreaker(
          getClass().getSimpleName() + "-findById",
          CircuitBreakerConfig.custom()
              .ignoreException(e -> e instanceof NotFoundException)
              .build());

  Supplier<T> recoverableSupplier =
      SupplierUtils.recover(
          () -> service.loadObject(objectType, buildObjectKey(id)),
          e ->
              allItemsCache.get().stream()
                  .filter(item -> item.getId().equalsIgnoreCase(id))
                  .findFirst()
                  .orElseThrow(
                      () ->
                          new NotFoundException(
                              String.format(
                                  "No item found in cache with id of %s", id.toLowerCase()))));

  return breaker.executeSupplier(recoverableSupplier);
}
 
Example #6
Source File: StateTransitionMetricsTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithCircuitBreakerMetrics() throws Exception {
    CircuitBreakerConfig config =
        CircuitBreakerConfig.custom()
            .waitDurationInOpenState(Duration.ofMillis(150))
            .failureRateThreshold(50)
            .permittedNumberOfCallsInHalfOpenState(3)
            .slidingWindowSize(10)
            .build();
    CircuitBreaker circuitBreaker = CircuitBreakerRegistry.ofDefaults()
        .circuitBreaker("test", config);
    MetricRegistry metricRegistry = new MetricRegistry();

    metricRegistry.registerAll(CircuitBreakerMetrics.ofCircuitBreaker(circuitBreaker));
    circuitBreakerMetricsUsesFirstStateObjectInstance(circuitBreaker, metricRegistry);
}
 
Example #7
Source File: SpringApp.java    From tutorials with MIT License 6 votes vote down vote up
@Bean
public Customizer<Resilience4JCircuitBreakerFactory> specificCustomConfiguration2() {

    TimeLimiterConfig timeLimiterConfig = TimeLimiterConfig.custom()
            .timeoutDuration(Duration.ofSeconds(4))
            .build();
    CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()
            .failureRateThreshold(50)
            .waitDurationInOpenState(Duration.ofMillis(1000))
            .slidingWindowSize(2)
            .build();

    return factory -> factory.configure(builder -> builder.circuitBreakerConfig(circuitBreakerConfig)
                    .timeLimiterConfig(timeLimiterConfig).build(),
            "circuitBreaker1", "circuitBreaker2", "circuitBreaker3");
}
 
Example #8
Source File: CircuitBreakerMetricsPublisherTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
    registry = new CollectorRegistry();
    circuitBreakerMetricsPublisher = new CircuitBreakerMetricsPublisher();
    circuitBreakerMetricsPublisher.register(registry);
    circuitBreakerRegistry = CircuitBreakerRegistry
        .of(CircuitBreakerConfig.ofDefaults(), circuitBreakerMetricsPublisher);

    CircuitBreakerConfig configWithSlowCallThreshold = CircuitBreakerConfig.custom()
        .slowCallDurationThreshold(Duration.ofSeconds(1)).build();
    circuitBreaker = circuitBreakerRegistry
        .circuitBreaker("backendA", configWithSlowCallThreshold);

    // record some basic stats
    // SLOW_SUCCESS
    circuitBreaker.onSuccess(2000, TimeUnit.NANOSECONDS);
    circuitBreaker.onError(100, TimeUnit.NANOSECONDS, new RuntimeException("oops"));
    circuitBreaker.transitionToOpenState();
}
 
Example #9
Source File: TaggedCircuitBreakerMetricsTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    meterRegistry = new SimpleMeterRegistry();
    circuitBreakerRegistry = CircuitBreakerRegistry.ofDefaults();
    CircuitBreakerConfig configWithSlowCallThreshold = CircuitBreakerConfig.custom()
        .slowCallDurationThreshold(Duration.ofSeconds(1)).build();

    circuitBreaker = circuitBreakerRegistry
        .circuitBreaker("backendA", configWithSlowCallThreshold);
    // record some basic stats
    circuitBreaker.onSuccess(0, TimeUnit.NANOSECONDS);
    circuitBreaker.onError(0, TimeUnit.NANOSECONDS, new RuntimeException("oops"));
    // record slow calls
    circuitBreaker.onSuccess(2000, TimeUnit.NANOSECONDS);
    circuitBreaker.onError(2000, TimeUnit.NANOSECONDS, new RuntimeException("oops"));

    taggedCircuitBreakerMetrics = TaggedCircuitBreakerMetrics
        .ofCircuitBreakerRegistry(circuitBreakerRegistry);
    taggedCircuitBreakerMetrics.bindTo(meterRegistry);
}
 
Example #10
Source File: StateTransitionMetricsTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithCircuitBreakerMetricsPublisher() throws Exception {
    CircuitBreakerConfig config =
        CircuitBreakerConfig.custom()
            .waitDurationInOpenState(Duration.ofSeconds(1))
            .failureRateThreshold(50)
            .permittedNumberOfCallsInHalfOpenState(3)
            .slidingWindowSize(10)
            .build();
    MetricRegistry metricRegistry = new MetricRegistry();
    CircuitBreakerRegistry circuitBreakerRegistry = CircuitBreakerRegistry
        .of(config, new CircuitBreakerMetricsPublisher(metricRegistry));
    CircuitBreaker circuitBreaker = circuitBreakerRegistry.circuitBreaker("test", config);

    circuitBreakerMetricsUsesFirstStateObjectInstance(circuitBreaker, metricRegistry);
}
 
Example #11
Source File: Resilience4JCircuitBreakerIntegrationTest.java    From spring-cloud-circuitbreaker with Apache License 2.0 6 votes vote down vote up
@Bean
public Customizer<Resilience4JCircuitBreakerFactory> slowCustomizer() {
	return factory -> {
		factory.configure(
				builder -> builder
						.circuitBreakerConfig(CircuitBreakerConfig.ofDefaults())
						.timeLimiterConfig(TimeLimiterConfig.custom()
								.timeoutDuration(Duration.ofSeconds(2)).build()),
				"slow");
		factory.configureDefault(id -> new Resilience4JConfigBuilder(id)
				.timeLimiterConfig(TimeLimiterConfig.custom()
						.timeoutDuration(Duration.ofSeconds(4)).build())
				.circuitBreakerConfig(CircuitBreakerConfig.ofDefaults()).build());
		factory.addCircuitBreakerCustomizer(circuitBreaker -> circuitBreaker
				.getEventPublisher().onError(slowErrorConsumer)
				.onSuccess(slowSuccessConsumer), "slow");
		factory.addCircuitBreakerCustomizer(circuitBreaker -> circuitBreaker
				.getEventPublisher().onError(normalErrorConsumer)
				.onSuccess(normalSuccessConsumer), "normal");
	};
}
 
Example #12
Source File: CircuitBreakerConfigurationProperties.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
/**
 * decide which circuit breaker delay policy for open state will be configured based into the
 * configured properties
 *
 * @param properties the backend circuit breaker properties
 * @param builder    the circuit breaker config builder
 */
private void configureCircuitBreakerOpenStateIntervalFunction(InstanceProperties properties,
    CircuitBreakerConfig.Builder builder) {
    // these take precedence over deprecated properties. Setting one or the other will still work.
    if (properties.getWaitDurationInOpenState() != null
        && properties.getWaitDurationInOpenState().toMillis() > 0) {
        Duration waitDuration = properties.getWaitDurationInOpenState();
        if (properties.getEnableExponentialBackoff() != null
            && properties.getEnableExponentialBackoff()) {
            configureEnableExponentialBackoff(properties, builder, waitDuration);
        } else if (properties.getEnableRandomizedWait() != null
            && properties.getEnableRandomizedWait()) {
            configureEnableRandomizedWait(properties, builder, waitDuration);
        } else {
            builder.waitDurationInOpenState(properties.getWaitDurationInOpenState());
        }
    }
}
 
Example #13
Source File: CircuitBreakerConfigCustomizer.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
/**
 * A convenient method to create CircuitBreakerConfigCustomizer using {@link Consumer}
 *
 * @param instanceName the name of the instance
 * @param consumer     delegate call to Consumer when  {@link CircuitBreakerConfigCustomizer#customize(CircuitBreakerConfig.Builder)}
 *                     is called
 * @return Customizer instance
 */
static CircuitBreakerConfigCustomizer of(@NonNull String instanceName,
    @NonNull Consumer<CircuitBreakerConfig.Builder> consumer) {
    return new CircuitBreakerConfigCustomizer() {

        @Override
        public void customize(CircuitBreakerConfig.Builder builder) {
            consumer.accept(builder);
        }

        @Override
        public String name() {
            return instanceName;
        }
    };
}
 
Example #14
Source File: Resilience4jTest.java    From spring-cloud-formula with Apache License 2.0 6 votes vote down vote up
@Before
public void init() {
    TimeLimiterConfig timeLimiterConfig = TimeLimiterConfig.custom()
            .timeoutDuration(Duration.ofSeconds(1))
            .cancelRunningFuture(true)
            .build();
     timeLimiter = TimeLimiter.of(timeLimiterConfig);

    CustomizableThreadFactory factory = new CustomizableThreadFactory("timeLimiter-");
    factory.setDaemon(true);
    executorService = Executors.newCachedThreadPool(factory);

    CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig
            .custom()
            .enableAutomaticTransitionFromOpenToHalfOpen()
            .failureRateThreshold(50)
            .ringBufferSizeInClosedState(10)
            .ringBufferSizeInHalfOpenState(2)
            .build();

    circuitBreaker = CircuitBreaker.of("backendName", circuitBreakerConfig);
}
 
Example #15
Source File: Resilience4jUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenCircuitBreakerIsUsed_thenItWorksAsExpected() {
    CircuitBreakerConfig config = CircuitBreakerConfig.custom()
                                                      // Percentage of failures to start short-circuit
                                                      .failureRateThreshold(20)
                                                      // Min number of call attempts
                                                      .ringBufferSizeInClosedState(5)
                                                      .build();
    CircuitBreakerRegistry registry = CircuitBreakerRegistry.of(config);
    CircuitBreaker circuitBreaker = registry.circuitBreaker("my");
    Function<Integer, Integer> decorated = CircuitBreaker.decorateFunction(circuitBreaker, service::process);

    when(service.process(anyInt())).thenThrow(new RuntimeException());

    for (int i = 0; i < 10; i++) {
        try {
            decorated.apply(i);
        } catch (Exception ignore) {
        }
    }

    verify(service, times(5)).process(any(Integer.class));
}
 
Example #16
Source File: CircuitBreakerMetrics.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
private CircuitBreakerMetrics(int slidingWindowSize,
    CircuitBreakerConfig.SlidingWindowType slidingWindowType,
    CircuitBreakerConfig circuitBreakerConfig,
    Clock clock) {
    if (slidingWindowType == CircuitBreakerConfig.SlidingWindowType.COUNT_BASED) {
        this.metrics = new FixedSizeSlidingWindowMetrics(slidingWindowSize);
        this.minimumNumberOfCalls = Math
            .min(circuitBreakerConfig.getMinimumNumberOfCalls(), slidingWindowSize);
    } else {
        this.metrics = new SlidingTimeWindowMetrics(slidingWindowSize, clock);
        this.minimumNumberOfCalls = circuitBreakerConfig.getMinimumNumberOfCalls();
    }
    this.failureRateThreshold = circuitBreakerConfig.getFailureRateThreshold();
    this.slowCallRateThreshold = circuitBreakerConfig.getSlowCallRateThreshold();
    this.slowCallDurationThresholdInNanos = circuitBreakerConfig.getSlowCallDurationThreshold()
        .toNanos();
    this.numberOfNotPermittedCalls = new LongAdder();
}
 
Example #17
Source File: InMemoryCircuitBreakerRegistryTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreateCircuitBreakerRegistryWithRegistryStore() {
    RegistryEventConsumer<CircuitBreaker> registryEventConsumer = getNoOpsRegistryEventConsumer();
    List<RegistryEventConsumer<CircuitBreaker>> registryEventConsumers = new ArrayList<>();
    registryEventConsumers.add(registryEventConsumer);
    Map<String, CircuitBreakerConfig> configs = new HashMap<>();
    final CircuitBreakerConfig defaultConfig = CircuitBreakerConfig.ofDefaults();
    configs.put("default", defaultConfig);
    final InMemoryCircuitBreakerRegistry inMemoryCircuitBreakerRegistry =
        new InMemoryCircuitBreakerRegistry(configs, registryEventConsumers,
            io.vavr.collection.HashMap.of("Tag1", "Tag1Value"), new InMemoryRegistryStore());

    assertThat(inMemoryCircuitBreakerRegistry).isNotNull();
    assertThat(inMemoryCircuitBreakerRegistry.getDefaultConfig()).isEqualTo(defaultConfig);
    assertThat(inMemoryCircuitBreakerRegistry.getConfiguration("testNotFound")).isEmpty();
    inMemoryCircuitBreakerRegistry.addConfiguration("testConfig", defaultConfig);
    assertThat(inMemoryCircuitBreakerRegistry.getConfiguration("testConfig")).isNotNull();
}
 
Example #18
Source File: CircuitBreakerConfigurationPropertiesTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testCircuitBreakerIntervalFunctionProperties() {
    //Given
    CircuitBreakerConfigurationProperties.InstanceProperties instanceProperties1 = new CircuitBreakerConfigurationProperties.InstanceProperties();
    instanceProperties1.setWaitDurationInOpenState(Duration.ofMillis(1000));
    instanceProperties1.setEnableExponentialBackoff(false);
    instanceProperties1.setEnableRandomizedWait(false);

    CircuitBreakerConfigurationProperties.InstanceProperties instanceProperties2 = new CircuitBreakerConfigurationProperties.InstanceProperties();
    instanceProperties2.setEnableExponentialBackoff(true);
    instanceProperties2.setExponentialBackoffMultiplier(1.0);
    instanceProperties2.setWaitDurationInOpenState(Duration.ofMillis(100L));

    CircuitBreakerConfigurationProperties circuitBreakerConfigurationProperties = new CircuitBreakerConfigurationProperties();
    circuitBreakerConfigurationProperties.getInstances().put("backend1", instanceProperties1);
    circuitBreakerConfigurationProperties.getInstances().put("backend2", instanceProperties2);
    Map<String, String> globalTagsForCircuitBreakers = new HashMap<>();
    globalTagsForCircuitBreakers.put("testKey1", "testKet2");
    circuitBreakerConfigurationProperties.setTags(globalTagsForCircuitBreakers);
    //Then
    assertThat(circuitBreakerConfigurationProperties.getInstances().size()).isEqualTo(2);
    assertThat(circuitBreakerConfigurationProperties.getTags()).isNotEmpty();
    assertThat(circuitBreakerConfigurationProperties.getBackends().size()).isEqualTo(2);
    final CircuitBreakerConfig circuitBreakerConfig1 = circuitBreakerConfigurationProperties
        .createCircuitBreakerConfig("backend1", instanceProperties1,
            compositeCircuitBreakerCustomizer());
    final CircuitBreakerConfig circuitBreakerConfig2 = circuitBreakerConfigurationProperties
        .createCircuitBreakerConfig("backend2", instanceProperties2,
            compositeCircuitBreakerCustomizer());
    CircuitBreakerConfigurationProperties.InstanceProperties instancePropertiesForRetry1 = circuitBreakerConfigurationProperties
        .getInstances().get("backend1");
    assertThat(instancePropertiesForRetry1.getWaitDurationInOpenState().toMillis())
        .isEqualTo(1000);
    assertThat(circuitBreakerConfig1).isNotNull();
    assertThat(circuitBreakerConfig1.getWaitIntervalFunctionInOpenState()).isNotNull();
    assertThat(circuitBreakerConfig2).isNotNull();
    assertThat(circuitBreakerConfig2.getWaitIntervalFunctionInOpenState()).isNotNull();


}
 
Example #19
Source File: CircuitBreakerMetricsPublisherTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Override
protected CircuitBreaker givenMetricRegistry(String prefix, MetricRegistry metricRegistry) {
    circuitBreakerRegistry = CircuitBreakerRegistry.of(CircuitBreakerConfig.ofDefaults(),
            new CircuitBreakerMetricsPublisher(prefix, metricRegistry));

    return circuitBreakerRegistry.circuitBreaker("testName");
}
 
Example #20
Source File: InMemoryCircuitBreakerRegistryTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateCircuitBreakerWithSharedConfiguration() {
    CircuitBreakerRegistry circuitBreakerRegistry = CircuitBreakerRegistry.ofDefaults();
    circuitBreakerRegistry.addConfiguration("testConfig", CircuitBreakerConfig.ofDefaults());

    final CircuitBreaker circuitBreaker = circuitBreakerRegistry
        .circuitBreaker("circuitBreaker",
            circuitBreakerRegistry.getConfiguration("testConfig").get());

    assertThat(circuitBreaker).isNotNull();
}
 
Example #21
Source File: CircuitBreakerConfigurationProperties.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
private CircuitBreakerConfig buildConfigFromBaseConfig(InstanceProperties instanceProperties,
    InstanceProperties baseProperties,
    CompositeCustomizer<CircuitBreakerConfigCustomizer> compositeCircuitBreakerCustomizer,
    String backendName) {
    ConfigUtils.mergePropertiesIfAny(instanceProperties, baseProperties);
    CircuitBreakerConfig baseConfig = buildConfig(custom(), baseProperties,
        compositeCircuitBreakerCustomizer,
        backendName);
    return buildConfig(from(baseConfig), instanceProperties, compositeCircuitBreakerCustomizer,
        backendName);
}
 
Example #22
Source File: CircuitBreakerConfigurationProperties.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
public CircuitBreakerConfig createCircuitBreakerConfig(String backendName,
    InstanceProperties instanceProperties,
    CompositeCustomizer<CircuitBreakerConfigCustomizer> compositeCircuitBreakerCustomizer) {
    if (StringUtils.isNotEmpty(instanceProperties.getBaseConfig())) {
        InstanceProperties baseProperties = configs.get(instanceProperties.getBaseConfig());
        if (baseProperties == null) {
            throw new ConfigurationNotFoundException(instanceProperties.getBaseConfig());
        }
        return buildConfigFromBaseConfig(instanceProperties, baseProperties,
            compositeCircuitBreakerCustomizer,
            backendName);
    }
    return buildConfig(custom(), instanceProperties, compositeCircuitBreakerCustomizer,
        backendName);
}
 
Example #23
Source File: CircuitBreakersHealthIndicatorTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
private void setCircuitBreakerWhen(CircuitBreaker.State givenState, CircuitBreaker circuitBreaker,
                                   CircuitBreakerConfig config, CircuitBreaker.Metrics metrics,
                                   io.github.resilience4j.common.circuitbreaker.configuration.CircuitBreakerConfigurationProperties.InstanceProperties instanceProperties,
                                   CircuitBreakerConfigurationProperties circuitBreakerProperties,
                                   boolean allowHealthIndicatorToFail) {

    when(circuitBreaker.getName()).thenReturn(givenState.name());
    when(circuitBreaker.getState()).thenReturn(givenState);
    when(circuitBreaker.getCircuitBreakerConfig()).thenReturn(config);
    when(circuitBreaker.getMetrics()).thenReturn(metrics);
    when(circuitBreakerProperties.findCircuitBreakerProperties(givenState.name()))
        .thenReturn(Optional.of(instanceProperties));
    when(instanceProperties.getRegisterHealthIndicator()).thenReturn(true);
    when(instanceProperties.getAllowHealthIndicatorToFail()).thenReturn(allowHealthIndicatorToFail);
}
 
Example #24
Source File: CircularEventConsumerTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldBufferAllEvents() {
    CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()
        .slidingWindowSize(3)
        .ignoreExceptions(IOException.class)
        .build();
    CircuitBreaker circuitBreaker = CircuitBreaker.of("testName", circuitBreakerConfig);
    CircularEventConsumer<CircuitBreakerEvent> ringBuffer = new CircularEventConsumer<>(10);
    circuitBreaker.getEventPublisher().onEvent(ringBuffer);
    assertThat(ringBuffer.getBufferedEvents()).isEmpty();

    circuitBreaker.onSuccess(0, TimeUnit.NANOSECONDS);
    circuitBreaker.onError(0, TimeUnit.NANOSECONDS, new RuntimeException("Bla"));
    circuitBreaker.onError(0, TimeUnit.NANOSECONDS, new IOException("Bla"));
    circuitBreaker.onError(0, TimeUnit.NANOSECONDS, new RuntimeException("Bla"));

    CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
    assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(3);
    assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(2);
    circuitBreaker.reset();
    CircuitBreaker.Metrics resetMetrics = circuitBreaker.getMetrics();
    assertThat(resetMetrics.getNumberOfBufferedCalls()).isEqualTo(0);
    assertThat(resetMetrics.getNumberOfFailedCalls()).isEqualTo(0);
    //Because circuit emits 2 error events and one state transition event
    assertThat(ringBuffer.getBufferedEvents()).hasSize(8);
    assertThat(ringBuffer.getBufferedEvents()).extracting("eventType")
        .containsExactly(Type.SUCCESS, Type.ERROR, Type.IGNORED_ERROR, Type.ERROR,
            Type.FAILURE_RATE_EXCEEDED, Type.STATE_TRANSITION, Type.STATE_TRANSITION,
            Type.RESET);
}
 
Example #25
Source File: CircuitBreakerMetricsPublisherTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Override
protected CircuitBreaker givenMetricRegistry(MetricRegistry metricRegistry) {
    circuitBreakerRegistry = CircuitBreakerRegistry.of(CircuitBreakerConfig.ofDefaults(),
            new CircuitBreakerMetricsPublisher(metricRegistry));

    return circuitBreakerRegistry.circuitBreaker("testName");
}
 
Example #26
Source File: CircuitBreakersHealthIndicatorTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void healthIndicatorMaxImpactCanBeOverridden() {
    CircuitBreaker openCircuitBreaker = mock(CircuitBreaker.class);
    CircuitBreaker halfOpenCircuitBreaker = mock(CircuitBreaker.class);
    CircuitBreaker closeCircuitBreaker = mock(CircuitBreaker.class);

    Map<CircuitBreaker.State, CircuitBreaker> expectedStateToCircuitBreaker = new HashMap<>();
    expectedStateToCircuitBreaker.put(OPEN, openCircuitBreaker);
    expectedStateToCircuitBreaker.put(HALF_OPEN, halfOpenCircuitBreaker);
    expectedStateToCircuitBreaker.put(CLOSED, closeCircuitBreaker);
    CircuitBreakerConfigurationProperties.InstanceProperties instanceProperties =
        mock(CircuitBreakerConfigurationProperties.InstanceProperties.class);
    CircuitBreakerConfigurationProperties circuitBreakerProperties = mock(CircuitBreakerConfigurationProperties.class);

    // given
    CircuitBreakerRegistry registry = mock(CircuitBreakerRegistry.class);
    CircuitBreakerConfig config = mock(CircuitBreakerConfig.class);
    CircuitBreaker.Metrics metrics = mock(CircuitBreaker.Metrics.class);

    // when
    when(registry.getAllCircuitBreakers()).thenReturn(Array.ofAll(expectedStateToCircuitBreaker.values()));
    boolean allowHealthIndicatorToFail = false;  // do not allow health indicator to fail
    expectedStateToCircuitBreaker.forEach(
        (state, circuitBreaker) -> setCircuitBreakerWhen(state, circuitBreaker, config, metrics, instanceProperties, circuitBreakerProperties, allowHealthIndicatorToFail));

    CircuitBreakersHealthIndicator healthIndicator =
        new CircuitBreakersHealthIndicator(registry, circuitBreakerProperties, new SimpleStatusAggregator());


    // then
    Health health = healthIndicator.health();

    then(health.getStatus()).isEqualTo(Status.UP);
    then(health.getDetails()).containsKeys(OPEN.name(), HALF_OPEN.name(), CLOSED.name());

    assertState(OPEN, new Status("CIRCUIT_OPEN"), health.getDetails());
    assertState(HALF_OPEN, new Status("CIRCUIT_HALF_OPEN"), health.getDetails());
    assertState(CLOSED, Status.UP, health.getDetails());

}
 
Example #27
Source File: InMemoryCircuitBreakerRegistryTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateCircuitBreakerWithConfigName() {
    CircuitBreakerRegistry circuitBreakerRegistry = CircuitBreakerRegistry.ofDefaults();
    circuitBreakerRegistry.addConfiguration("testConfig",
        CircuitBreakerConfig.custom().slidingWindowSize(5).build());

    final CircuitBreaker circuitBreaker = circuitBreakerRegistry
        .circuitBreaker("circuitBreaker",
            "testConfig");

    assertThat(circuitBreaker).isNotNull();
    assertThat(circuitBreaker.getCircuitBreakerConfig().getSlidingWindowSize()).isEqualTo(5);
}
 
Example #28
Source File: CircuitBreakerConfiguration.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes a circuitBreaker registry.
 *
 * @param circuitBreakerProperties The circuit breaker configuration properties.
 * @param customizerMap
 * @return a CircuitBreakerRegistry
 */
CircuitBreakerRegistry createCircuitBreakerRegistry(
    CircuitBreakerConfigurationProperties circuitBreakerProperties,
    RegistryEventConsumer<CircuitBreaker> circuitBreakerRegistryEventConsumer,
    CompositeCustomizer<CircuitBreakerConfigCustomizer> customizerMap) {

    Map<String, CircuitBreakerConfig> configs = circuitBreakerProperties.getConfigs()
        .entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,
            entry -> circuitBreakerProperties
                .createCircuitBreakerConfig(entry.getKey(), entry.getValue(),
                    customizerMap)));

    return CircuitBreakerRegistry.of(configs, circuitBreakerRegistryEventConsumer,
        io.vavr.collection.HashMap.ofAll(circuitBreakerProperties.getTags()));
}
 
Example #29
Source File: InMemoryCircuitBreakerRegistryTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddCircuitBreakerRegistry() {
    CircuitBreakerRegistry circuitBreakerRegistry = CircuitBreakerRegistry.ofDefaults();
    circuitBreakerRegistry.addConfiguration("testConfig", CircuitBreakerConfig.ofDefaults());

    assertThat(circuitBreakerRegistry.getConfiguration("testConfig")).isNotNull();
}
 
Example #30
Source File: ReactiveResilience4JCircuitbreakerDemoApplication.java    From spring-cloud-circuitbreaker-demo with Apache License 2.0 5 votes vote down vote up
@Bean
public Customizer<ReactiveResilience4JCircuitBreakerFactory> defaultCustomizer() {
	CircuitBreakerRegistry cbr = CircuitBreakerRegistry.ofDefaults();
	return factory -> {
		factory.configureDefault(id -> new Resilience4JConfigBuilder(id)
				.circuitBreakerConfig(CircuitBreakerConfig.ofDefaults())
				.timeLimiterConfig(TimeLimiterConfig.custom().timeoutDuration(Duration.ofSeconds(3)).build())
				.circuitBreakerConfig(CircuitBreakerConfig.custom().failureRateThreshold(10)
						.slowCallRateThreshold(5).slowCallRateThreshold(2).build()).build());
	};
}