Java Code Examples for io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry#of()

The following examples show how to use io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry#of() . 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: 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 2
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 3
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 4
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 5
Source File: ResilienceHandler.java    From cloud-espm-cloud-native with Apache License 2.0 5 votes vote down vote up
/**
 * Creating a circuit breaker using custom configuration
 * 
 * @return
 */
private CircuitBreaker configureCircuitBreaker() {
	CircuitBreakerConfig circuitBreakerConfig = 
			CircuitBreakerConfig.custom()
								.failureRateThreshold(20)
								.waitDurationInOpenState(Duration.ofMillis(3000))
								.ringBufferSizeInClosedState(10)
								.ringBufferSizeInHalfOpenState(5).build();
	CircuitBreakerRegistry circuitBreakerRegistry = CircuitBreakerRegistry.of(circuitBreakerConfig);
	CircuitBreaker circuitBreaker = circuitBreakerRegistry.circuitBreaker("taxservice");
	return circuitBreaker;
}
 
Example 6
Source File: CircuitBreakerMetricsPublisherTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void customMetricNamesOverrideDefaultOnes() {
    CollectorRegistry registry = new CollectorRegistry();
    CircuitBreakerMetricsPublisher circuitBreakerMetricsPublisher = new CircuitBreakerMetricsPublisher(
        custom().callsMetricName("custom_calls")
            .stateMetricName("custom_state")
            .slowCallsMetricName("custom_slow_calls")
            .bufferedCallsMetricName("custom_buffered_calls")
            .failureRateMetricName("custom_failure_rate")
            .slowCallRateMetricName("custom_slow_rate")
            .build()
    );
    circuitBreakerMetricsPublisher.register(registry);
    CircuitBreakerRegistry circuitBreakerRegistry = CircuitBreakerRegistry
        .of(CircuitBreakerConfig.ofDefaults(), circuitBreakerMetricsPublisher);
    circuitBreakerRegistry.circuitBreaker("backendA");

    assertThat(registry.getSampleValue(
        "custom_buffered_calls",
        new String[]{"name", "kind"},
        new String[]{"backendA", "successful"}
    )).isNotNull();
    assertThat(registry.getSampleValue(
        "custom_buffered_calls",
        new String[]{"name", "kind"},
        new String[]{"backendA", "failed"}
    )).isNotNull();
    assertThat(registry.getSampleValue(
        "custom_state",
        new String[]{"name", "state"},
        new String[]{"backendA", "closed"}
    )).isNotNull();
}
 
Example 7
Source File: CircuitBreakerMetricsPublisherTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void customMetricNameBucketsOverrideDefaultOnes() {
    CollectorRegistry registry = new CollectorRegistry();

    CircuitBreakerMetricsPublisher circuitBreakerMetricsPublisher = new CircuitBreakerMetricsPublisher(
        MetricNames.ofDefaults(),
        MetricOptions.custom().buckets(new double[]{.005, .01}).build());

    circuitBreakerMetricsPublisher.register(registry);
    CircuitBreakerRegistry circuitBreakerRegistry = CircuitBreakerRegistry
        .of(CircuitBreakerConfig.ofDefaults(), circuitBreakerMetricsPublisher);
    CircuitBreaker circuitBreaker = circuitBreakerRegistry.circuitBreaker("backendA");

    circuitBreaker.onSuccess(2000, TimeUnit.NANOSECONDS);

    assertThat(registry.getSampleValue(
        DEFAULT_CIRCUIT_BREAKER_CALLS + "_bucket",
        new String[]{"name", "kind", "le"},
        new String[]{circuitBreaker.getName(), "successful", "0.01"}
    )).isEqualTo(1d);

    assertThat(registry.getSampleValue(
        DEFAULT_CIRCUIT_BREAKER_CALLS + "_bucket",
        new String[]{"name", "kind", "le"},
        new String[]{circuitBreaker.getName(), "successful", "0.025"}
    )).isNull();
}
 
Example 8
Source File: TaggedCircuitBreakerMetricsPublisherTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void metricsAreRegisteredWithCustomName() {
    MeterRegistry meterRegistry = new SimpleMeterRegistry();
    TaggedCircuitBreakerMetricsPublisher taggedCircuitBreakerMetricsPublisher = new TaggedCircuitBreakerMetricsPublisher(
        CircuitBreakerMetricNames.custom()
            .callsMetricName("custom_calls")
            .notPermittedCallsMetricName("custom_not_permitted_calls")
            .stateMetricName("custom_state")
            .bufferedCallsMetricName("custom_buffered_calls")
            .slowCallsMetricName("custom_slow_calls")
            .failureRateMetricName("custom_failure_rate")
            .slowCallRateMetricName("custom_slow_call_rate")
            .build(), meterRegistry
    );
    CircuitBreakerRegistry circuitBreakerRegistry = CircuitBreakerRegistry
        .of(CircuitBreakerConfig.ofDefaults(), taggedCircuitBreakerMetricsPublisher);
    circuitBreakerRegistry.circuitBreaker("backendA");

    Set<String> metricNames = meterRegistry.getMeters()
        .stream()
        .map(Meter::getId)
        .map(Meter.Id::getName)
        .collect(Collectors.toSet());

    assertThat(metricNames).hasSameElementsAs(Arrays.asList(
        "custom_calls",
        "custom_not_permitted_calls",
        "custom_state",
        "custom_buffered_calls",
        "custom_slow_calls",
        "custom_failure_rate",
        "custom_slow_call_rate"
    ));
}
 
Example 9
Source File: Resilience4jModule.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Override
public CircuitBreakerRegistry get() {
    // build configs
    CircuitBreakerConfigurationProperties circuitBreakerProperties = resilience4jConfig
        .getCircuitbreaker();
    Map<String, CircuitBreakerConfig> configs = circuitBreakerProperties.getConfigs()
        .entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,
            entry -> circuitBreakerProperties
                .createCircuitBreakerConfig(entry.getKey(), entry.getValue(),
                    new CompositeCustomizer<>(Collections.emptyList()))));
    CircuitBreakerRegistry circuitBreakerRegistry = CircuitBreakerRegistry.of(configs);

    // build circuit breakers
    EndpointsConfig endpointsConfig = resilience4jConfig.getEndpoints();
    circuitBreakerProperties.getInstances().forEach((name, circuitBreakerConfig) -> {
        io.github.resilience4j.circuitbreaker.CircuitBreaker circuitBreaker =
            circuitBreakerRegistry.circuitBreaker(name,
                circuitBreakerProperties.createCircuitBreakerConfig(name,
                    circuitBreakerConfig,
                    new CompositeCustomizer<>(Collections.emptyList())));
        if (endpointsConfig.getCircuitbreaker().isEnabled()) {
            circuitBreaker.getEventPublisher().onEvent(eventConsumerRegistry
                .createEventConsumer(name,
                    circuitBreakerConfig.getEventConsumerBufferSize() != null
                        ? circuitBreakerConfig.getEventConsumerBufferSize() : 100));
        }
    });

    return circuitBreakerRegistry;
}
 
Example 10
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 11
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 12
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");
}