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

The following examples show how to use io.github.resilience4j.circuitbreaker.CircuitBreaker#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: 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 2
Source File: RetrofitCircuitBreakerTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    this.circuitBreaker = CircuitBreaker.of("test", circuitBreakerConfig);

    final long TIMEOUT = 150; // ms
    this.client = new OkHttpClient.Builder()
        .connectTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
        .readTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
        .writeTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
        .build();

    this.service = new Retrofit.Builder()
        .addCallAdapterFactory(CircuitBreakerCallAdapter.of(circuitBreaker))
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .addConverterFactory(ScalarsConverterFactory.create())
        .baseUrl(wireMockRule.baseUrl())
        .client(client)
        .build()
        .create(RetrofitService.class);
}
 
Example 3
Source File: CircuitBreakerManager.java    From spring-cloud-formula with Apache License 2.0 5 votes vote down vote up
private CircuitBreakerCoalition createCircuitBreaker(String ruleName, CircuitBreakerRule rule) {
    if (rule == null) {
        return null;
    }
    if (rule.getEnabled() != null && rule.getEnabled() && rule.getFailureRateThreshold() != null) {
        try {
            CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()
                    .failureRateThreshold(rule.getFailureRateThreshold())
                    .waitDurationInOpenState(rule.getWaitDurationInOpenState())
                    .ringBufferSizeInHalfOpenState(rule.getRingBufferSizeInHalfOpenState())
                    .ringBufferSizeInClosedState(rule.getRingBufferSizeInClosedState())
                    .build();

            CircuitBreaker circuitBreaker = CircuitBreaker.of(ruleName, circuitBreakerConfig);
            if (rule.getForceOpen() != null && rule.getForceOpen()) {
                circuitBreaker.transitionToForcedOpenState();
            }
            CircuitBreakerCoalition circuitBreakerCoalition = new CircuitBreakerCoalition(
                    circuitBreaker, rule);
            return circuitBreakerCoalition;
        } catch (Throwable e) {
            logger.error("failed to create circuitBreaker,name:{},id{}",
                    ruleName, rule.getRuleId(), e);
            return null;
        }
    }
    return null;
}
 
Example 4
Source File: Resilience4jFeignCircuitBreakerTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    circuitBreaker = CircuitBreaker.of("test", circuitBreakerConfig);
    final FeignDecorators decorators = FeignDecorators.builder()
        .withCircuitBreaker(circuitBreaker).build();
    testService = Resilience4jFeign.builder(decorators)
        .target(TestService.class, "http://localhost:8080/");
}
 
Example 5
Source File: TaggedCircuitBreakerMetricsPublisherTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testReplaceNewMeter(){
    CircuitBreaker oldOne = CircuitBreaker.of("backendC", CircuitBreakerConfig.ofDefaults());
    // add meters of old
    taggedCircuitBreakerMetricsPublisher.addMetrics(meterRegistry, oldOne);
    // one success call
    oldOne.onSuccess(0, TimeUnit.NANOSECONDS);

    assertThat(taggedCircuitBreakerMetricsPublisher.meterIdMap).containsKeys("backendC");
    assertThat(taggedCircuitBreakerMetricsPublisher.meterIdMap.get("backendC")).hasSize(16);
    Collection<Gauge> gauges = meterRegistry.get(DEFAULT_CIRCUIT_BREAKER_BUFFERED_CALLS).gauges();
    Optional<Gauge> successful = findMeterByKindAndNameTags(gauges, "successful", oldOne.getName());
    assertThat(successful).isPresent();
    assertThat(successful.get().value())
        .isEqualTo(oldOne.getMetrics().getNumberOfSuccessfulCalls());

    CircuitBreaker newOne = CircuitBreaker.of("backendC", CircuitBreakerConfig.ofDefaults());

    // add meters of new
    taggedCircuitBreakerMetricsPublisher.addMetrics(meterRegistry, newOne);
    // three success call
    newOne.onSuccess(0, TimeUnit.NANOSECONDS);
    newOne.onSuccess(0, TimeUnit.NANOSECONDS);
    newOne.onSuccess(0, TimeUnit.NANOSECONDS);

    assertThat(taggedCircuitBreakerMetricsPublisher.meterIdMap).containsKeys("backendC");
    assertThat(taggedCircuitBreakerMetricsPublisher.meterIdMap.get("backendC")).hasSize(16);
    gauges = meterRegistry.get(DEFAULT_CIRCUIT_BREAKER_BUFFERED_CALLS).gauges();
    successful = findMeterByKindAndNameTags(gauges, "successful", newOne.getName());
    assertThat(successful).isPresent();
    assertThat(successful.get().value())
        .isEqualTo(newOne.getMetrics().getNumberOfSuccessfulCalls());

}
 
Example 6
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);
}