io.github.resilience4j.bulkhead.BulkheadConfig Java Examples

The following examples show how to use io.github.resilience4j.bulkhead.BulkheadConfig. 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: TaggedBulkheadMetricsTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReplaceMetrics() {
    Collection<Gauge> gauges = meterRegistry
        .get(DEFAULT_BULKHEAD_MAX_ALLOWED_CONCURRENT_CALLS_METRIC_NAME).gauges();

    Optional<Gauge> successful = findMeterByNamesTag(gauges, bulkhead.getName());
    assertThat(successful).isPresent();
    assertThat(successful.get().value())
        .isEqualTo(bulkhead.getMetrics().getMaxAllowedConcurrentCalls());

    Bulkhead newBulkhead = Bulkhead.of(bulkhead.getName(), BulkheadConfig.custom()
        .maxConcurrentCalls(100).build());

    bulkheadRegistry.replace(bulkhead.getName(), newBulkhead);

    gauges = meterRegistry.get(DEFAULT_BULKHEAD_MAX_ALLOWED_CONCURRENT_CALLS_METRIC_NAME)
        .gauges();

    successful = findMeterByNamesTag(gauges, newBulkhead.getName());
    assertThat(successful).isPresent();
    assertThat(successful.get().value())
        .isEqualTo(newBulkhead.getMetrics().getMaxAllowedConcurrentCalls());

}
 
Example #2
Source File: AbstractBulkheadMetricsTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void bulkheadConfigChangeAffectsTheMaxAllowedConcurrentCallsValue() {
    Bulkhead bulkhead = givenMetricRegistry("testPre", metricRegistry);
    // Then make sure that configured value is reported as max allowed concurrent calls
    assertThat(
        metricRegistry.getGauges().get("testPre.testBulkhead.max_allowed_concurrent_calls")
            .getValue())
        .isEqualTo(DEFAULT_MAX_CONCURRENT_CALLS);

    // And when the config is changed
    BulkheadConfig newConfig = BulkheadConfig.custom()
        .maxConcurrentCalls(DEFAULT_MAX_CONCURRENT_CALLS + 50)
        .build();
    bulkhead.changeConfig(newConfig);

    // Then the new config value gets reported
    assertThat(
        metricRegistry.getGauges().get("testPre.testBulkhead.max_allowed_concurrent_calls")
            .getValue())
        .isEqualTo(newConfig.getMaxConcurrentCalls());
}
 
Example #3
Source File: SemaphoreBulkheadTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testTryEnterWithTimeout() throws InterruptedException {
    long expectedMillisOfWaitTime = 50;
    BulkheadConfig config = BulkheadConfig.custom()
        .maxConcurrentCalls(1)
        .maxWaitDuration(Duration.ofMillis(expectedMillisOfWaitTime))
        .build();
    SemaphoreBulkhead bulkhead = new SemaphoreBulkhead("test", config);

    boolean entered = bulkhead.tryEnterBulkhead();
    Thread subTestRoutine = new Thread(() -> {
        long start = System.nanoTime();
        boolean acquired = bulkhead.tryAcquirePermission();
        Duration actualWaitTime = Duration.ofNanos(System.nanoTime() - start);
        assertThat(acquired).isFalse();
        assertThat(actualWaitTime.toMillis())
            .isBetween(expectedMillisOfWaitTime, (long) (expectedMillisOfWaitTime * 1.3));
    });
    subTestRoutine.setDaemon(true);
    subTestRoutine.start();

    assertThat(entered).isTrue();
    subTestRoutine.join(2 * expectedMillisOfWaitTime);
    assertThat(subTestRoutine.isInterrupted()).isFalse();
    assertThat(subTestRoutine.isAlive()).isFalse();
}
 
Example #4
Source File: TaggedBulkheadMetricsPublisherTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReplaceMetrics() {
    Collection<Gauge> gauges = meterRegistry
        .get(DEFAULT_BULKHEAD_MAX_ALLOWED_CONCURRENT_CALLS_METRIC_NAME).gauges();

    Optional<Gauge> successful = findMeterByNamesTag(gauges, bulkhead.getName());
    assertThat(successful).isPresent();
    assertThat(successful.get().value())
        .isEqualTo(bulkhead.getMetrics().getMaxAllowedConcurrentCalls());

    Bulkhead newBulkhead = Bulkhead.of(bulkhead.getName(), BulkheadConfig.custom()
        .maxConcurrentCalls(100).build());

    bulkheadRegistry.replace(bulkhead.getName(), newBulkhead);

    gauges = meterRegistry.get(DEFAULT_BULKHEAD_MAX_ALLOWED_CONCURRENT_CALLS_METRIC_NAME)
        .gauges();

    successful = findMeterByNamesTag(gauges, newBulkhead.getName());
    assertThat(successful).isPresent();
    assertThat(successful.get().value())
        .isEqualTo(newBulkhead.getMetrics().getMaxAllowedConcurrentCalls());

}
 
Example #5
Source File: BulkheadConfigCustomizer.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
/**
 * A convenient method to create BulkheadConfigCustomizer using {@link Consumer}
 *
 * @param instanceName the name of the instance
 * @param consumer     delegate call to Consumer when  {@link BulkheadConfigCustomizer#customize(BulkheadConfig.Builder)}
 *                     is called
 * @return Customizer instance
 */
static  BulkheadConfigCustomizer of(@NonNull String instanceName,
    @NonNull Consumer<BulkheadConfig.Builder> consumer) {
    return new BulkheadConfigCustomizer() {

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

        @Override
        public String name() {
            return instanceName;
        }
    };
}
 
Example #6
Source File: TaggedBulkheadMetricsPublisherTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void customMetricNamesGetApplied() {
    MeterRegistry meterRegistry = new SimpleMeterRegistry();
    TaggedBulkheadMetricsPublisher taggedBulkheadMetricsPublisher = new TaggedBulkheadMetricsPublisher(
        BulkheadMetricNames.custom()
            .availableConcurrentCallsMetricName("custom_available_calls")
            .maxAllowedConcurrentCallsMetricName("custom_max_allowed_calls")
            .build(), meterRegistry);

    BulkheadRegistry bulkheadRegistry = BulkheadRegistry
        .of(BulkheadConfig.ofDefaults(), taggedBulkheadMetricsPublisher);
    bulkhead = bulkheadRegistry.bulkhead("backendA");

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

    assertThat(metricNames).hasSameElementsAs(Arrays.asList(
        "custom_available_calls",
        "custom_max_allowed_calls"
    ));
}
 
Example #7
Source File: SemaphoreBulkheadTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreateBulkheadRegistryWithRegistryStore() {
    RegistryEventConsumer<Bulkhead> registryEventConsumer = getNoOpsRegistryEventConsumer();
    List<RegistryEventConsumer<Bulkhead>> registryEventConsumers = new ArrayList<>();
    registryEventConsumers.add(registryEventConsumer);
    Map<String, BulkheadConfig> configs = new HashMap<>();
    final BulkheadConfig defaultConfig = BulkheadConfig.ofDefaults();
    configs.put("default", defaultConfig);
    final InMemoryBulkheadRegistry inMemoryBulkheadRegistry =
        new InMemoryBulkheadRegistry(configs, registryEventConsumers,
            io.vavr.collection.HashMap.of("Tag1", "Tag1Value"), new InMemoryRegistryStore());

    AssertionsForClassTypes.assertThat(inMemoryBulkheadRegistry).isNotNull();
    AssertionsForClassTypes.assertThat(inMemoryBulkheadRegistry.getDefaultConfig()).isEqualTo(defaultConfig);
    AssertionsForClassTypes.assertThat(inMemoryBulkheadRegistry.getConfiguration("testNotFound")).isEmpty();
    inMemoryBulkheadRegistry.addConfiguration("testConfig", defaultConfig);
    AssertionsForClassTypes.assertThat(inMemoryBulkheadRegistry.getConfiguration("testConfig")).isNotNull();
}
 
Example #8
Source File: SemaphoreBulkheadTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void changePermissionsInIdleState() {
    BulkheadConfig originalConfig = BulkheadConfig.custom()
        .maxConcurrentCalls(3)
        .maxWaitDuration(Duration.ofMillis(5000))
        .build();
    SemaphoreBulkhead bulkhead = new SemaphoreBulkhead("test", originalConfig);

    assertThat(bulkhead.getBulkheadConfig().getMaxConcurrentCalls()).isEqualTo(3);
    assertThat(bulkhead.getBulkheadConfig().getMaxWaitDuration().toMillis()).isEqualTo(5000);

    BulkheadConfig newConfig = BulkheadConfig.custom()
        .maxConcurrentCalls(5)
        .maxWaitDuration(Duration.ofMillis(5000))
        .build();

    bulkhead.changeConfig(newConfig);
    assertThat(bulkhead.getBulkheadConfig().getMaxConcurrentCalls()).isEqualTo(5);
    assertThat(bulkhead.getBulkheadConfig().getMaxWaitDuration().toMillis()).isEqualTo(5000);

    newConfig = BulkheadConfig.custom()
        .maxConcurrentCalls(2)
        .maxWaitDuration(Duration.ofMillis(5000))
        .build();

    bulkhead.changeConfig(newConfig);
    assertThat(bulkhead.getBulkheadConfig().getMaxConcurrentCalls()).isEqualTo(2);
    assertThat(bulkhead.getBulkheadConfig().getMaxWaitDuration().toMillis()).isEqualTo(5000);

    bulkhead.changeConfig(newConfig);
}
 
Example #9
Source File: Resilience4jFeignBulkheadTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    bulkhead = spy(Bulkhead.of("bulkheadTest", BulkheadConfig.ofDefaults()));
    final FeignDecorators decorators = FeignDecorators.builder()
            .withBulkhead(bulkhead)
            .build();
    testService = Resilience4jFeign.builder(decorators)
            .target(TestService.class, MOCK_URL);

}
 
Example #10
Source File: SemaphoreBulkheadTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void changeWaitingTimeWhileOneThreadIsWaitingForPermission() {
    BulkheadConfig originalConfig = BulkheadConfig.custom()
        .maxConcurrentCalls(1)
        .maxWaitDuration(Duration.ofMillis(500000))
        .build();
    SemaphoreBulkhead bulkhead = new SemaphoreBulkhead("test", originalConfig);
    assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1);
    bulkhead.tryAcquirePermission();
    assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(0);

    assertThat(bulkhead.getBulkheadConfig().getMaxConcurrentCalls()).isEqualTo(1);
    Thread bulkheadThread = new Thread(() -> {
        bulkhead.tryAcquirePermission();
        bulkhead.onComplete();
    });
    bulkheadThread.setDaemon(true);
    bulkheadThread.start();

    await().atMost(1, SECONDS)
        .until(() -> bulkheadThread.getState().equals(TIMED_WAITING));
    assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(0);

    BulkheadConfig newConfig = BulkheadConfig.custom()
        .maxConcurrentCalls(1)
        .maxWaitDuration(Duration.ofMillis(0))
        .build();

    bulkhead.changeConfig(newConfig);
    assertThat(bulkhead.tryEnterBulkhead()).isFalse(); // main thread is not blocked

    // previously blocked thread is still waiting
    await().atMost(1, SECONDS)
        .until(() -> bulkheadThread.getState().equals(TIMED_WAITING));
}
 
Example #11
Source File: SemaphoreBulkheadTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void changePermissionsCountWhileOneThreadIsWaitingForPermission() {
    BulkheadConfig originalConfig = BulkheadConfig.custom()
        .maxConcurrentCalls(1)
        .maxWaitDuration(Duration.ofMillis(500000))
        .build();
    SemaphoreBulkhead bulkhead = new SemaphoreBulkhead("test", originalConfig);
    assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1);
    bulkhead.tryAcquirePermission();
    assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(0);

    assertThat(bulkhead.getBulkheadConfig().getMaxConcurrentCalls()).isEqualTo(1);
    Thread bulkheadThread = new Thread(() -> {
        bulkhead.tryAcquirePermission();
        bulkhead.onComplete();
    });
    bulkheadThread.setDaemon(true);
    bulkheadThread.start();

    await().atMost(1, SECONDS)
        .until(() -> bulkheadThread.getState().equals(TIMED_WAITING));

    assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(0);

    BulkheadConfig newConfig = BulkheadConfig.custom()
        .maxConcurrentCalls(2)
        .maxWaitDuration(Duration.ofMillis(500000))
        .build();

    bulkhead.changeConfig(newConfig);
    await().atMost(1, SECONDS)
        .until(() -> bulkheadThread.getState().equals(TERMINATED));
    assertThat(bulkhead.getBulkheadConfig().getMaxConcurrentCalls()).isEqualTo(2);
    assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1);
}
 
Example #12
Source File: SemaphoreBulkheadTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void changeWaitTimeInIdleState() {
    BulkheadConfig originalConfig = BulkheadConfig.custom()
        .maxConcurrentCalls(3)
        .maxWaitDuration(Duration.ofMillis(5000))
        .build();
    SemaphoreBulkhead bulkhead = new SemaphoreBulkhead("test", originalConfig);

    assertThat(bulkhead.getBulkheadConfig().getMaxConcurrentCalls()).isEqualTo(3);
    assertThat(bulkhead.getBulkheadConfig().getMaxWaitDuration().toMillis()).isEqualTo(5000);

    BulkheadConfig newConfig = BulkheadConfig.custom()
        .maxConcurrentCalls(3)
        .maxWaitDuration(Duration.ofMillis(3000))
        .build();

    bulkhead.changeConfig(newConfig);
    assertThat(bulkhead.getBulkheadConfig().getMaxConcurrentCalls()).isEqualTo(3);
    assertThat(bulkhead.getBulkheadConfig().getMaxWaitDuration().toMillis()).isEqualTo(3000);

    newConfig = BulkheadConfig.custom()
        .maxConcurrentCalls(3)
        .maxWaitDuration(Duration.ofMillis(7000))
        .build();

    bulkhead.changeConfig(newConfig);
    assertThat(bulkhead.getBulkheadConfig().getMaxConcurrentCalls()).isEqualTo(3);
    assertThat(bulkhead.getBulkheadConfig().getMaxWaitDuration().toMillis()).isEqualTo(7000);

    bulkhead.changeConfig(newConfig);
}
 
Example #13
Source File: SemaphoreBulkhead.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void changeConfig(final BulkheadConfig newConfig) {
    synchronized (configChangesLock) {
        int delta = newConfig.getMaxConcurrentCalls() - config.getMaxConcurrentCalls();
        if (delta < 0) {
            semaphore.acquireUninterruptibly(-delta);
        } else if (delta > 0) {
            semaphore.release(delta);
        }
        config = newConfig;
    }
}
 
Example #14
Source File: SemaphoreBulkheadTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testEntryTimeout() {
    BulkheadConfig config = BulkheadConfig.custom()
        .maxConcurrentCalls(1)
        .maxWaitDuration(Duration.ofMillis(10))
        .build();
    SemaphoreBulkhead bulkhead = new SemaphoreBulkhead("test", config);
    bulkhead.tryAcquirePermission(); // consume the permit

    boolean entered = bulkhead.tryEnterBulkhead();

    assertThat(entered).isFalse();
}
 
Example #15
Source File: SemaphoreBulkheadTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testZeroMaxConcurrentCalls() {
    BulkheadConfig config = BulkheadConfig.custom()
        .maxConcurrentCalls(0)
        .maxWaitDuration(Duration.ofMillis(0))
        .build();
    SemaphoreBulkhead bulkhead = new SemaphoreBulkhead("test", config);

    boolean entered = bulkhead.tryAcquirePermission();

    assertThat(entered).isFalse();
}
 
Example #16
Source File: AsyncSqsClientImpl.java    From dynein with Apache License 2.0 5 votes vote down vote up
AsyncSqsClientImpl(
    @NonNull final SqsAsyncClient client,
    @NonNull final AsyncConveyorMetrics metrics,
    @NonNull final ExecutorService executor,
    long maxCacheSize,
    int receiveWaitTimeoutSeconds,
    int bulkheadMaxWaitMillis,
    int consumerConcurrency) {

  this.client = client;
  this.metrics = metrics;
  this.urlCache = initUrlCache(maxCacheSize);
  this.executor = executor;
  this.receiveWaitTimeoutSeconds = receiveWaitTimeoutSeconds;
  this.bulkhead =
      Bulkhead.of(
          "conveyor-async",
          BulkheadConfig.custom()
              .maxConcurrentCalls(consumerConcurrency)
              .maxWaitTimeDuration(Duration.ofMillis(bulkheadMaxWaitMillis))
              .build());
  this.bulkhead
      .getEventPublisher()
      .onCallPermitted(event -> metrics.consumePermitted())
      .onCallFinished(event -> metrics.consumeFinished())
      .onCallRejected(event -> metrics.consumeRejected())
      .onEvent(event -> metrics.bulkheadMetrics(this.bulkhead.getMetrics()));
}
 
Example #17
Source File: SemaphoreBulkheadTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateWithNullConfig() {
    Supplier<BulkheadConfig> configSupplier = () -> null;

    assertThatThrownBy(() -> Bulkhead.of("test", configSupplier))
        .isInstanceOf(NullPointerException.class).hasMessage("Config must not be null");
}
 
Example #18
Source File: SemaphoreBulkheadTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testTryEnterWithInterruptDuringTimeout() throws InterruptedException {
    Duration expectedWaitTime = Duration.ofMillis(2000);
    BulkheadConfig config = BulkheadConfig.custom()
        .maxConcurrentCalls(1)
        .maxWaitDuration(expectedWaitTime)
        .build();
    SemaphoreBulkhead bulkhead = new SemaphoreBulkhead("test", config);

    AtomicBoolean interruptedWithoutCodeFlowBreak = new AtomicBoolean(false);
    boolean entered = bulkhead.tryEnterBulkhead();
    Thread subTestRoutine = new Thread(() -> {
        long start = System.nanoTime();
        boolean acquired = bulkhead.tryAcquirePermission();
        Duration actualWaitTime = Duration.ofNanos(System.nanoTime() - start);
        assertThat(acquired).isFalse();
        assertThat(actualWaitTime).isLessThan(expectedWaitTime);
        assertThat(Thread.currentThread().isInterrupted()).isTrue();
        interruptedWithoutCodeFlowBreak.set(true);
    });
    subTestRoutine.setDaemon(true);
    subTestRoutine.start();

    await().atMost(expectedWaitTime.dividedBy(2).toMillis(), MILLISECONDS)
        .pollInterval(expectedWaitTime.dividedBy(100).toMillis(), MILLISECONDS)
        .until(() -> subTestRoutine.getState() == Thread.State.TIMED_WAITING);
    subTestRoutine.interrupt();
    await().atMost(expectedWaitTime.dividedBy(2).toMillis(), MILLISECONDS)
        .pollInterval(expectedWaitTime.dividedBy(100).toMillis(), MILLISECONDS)
        .until(() -> subTestRoutine.getState() == Thread.State.TERMINATED);
    assertThat(entered).isTrue();
    assertThat(interruptedWithoutCodeFlowBreak.get()).isTrue();
    assertThat(subTestRoutine.isAlive()).isFalse();
}
 
Example #19
Source File: TaggedBulkheadMetricsPublisherTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    meterRegistry = new SimpleMeterRegistry();
    taggedBulkheadMetricsPublisher = new TaggedBulkheadMetricsPublisher(meterRegistry);
    bulkheadRegistry = BulkheadRegistry
        .of(BulkheadConfig.ofDefaults(), taggedBulkheadMetricsPublisher);
    bulkhead = bulkheadRegistry.bulkhead("backendA");

    // record some basic stats
    bulkhead.tryAcquirePermission();
    bulkhead.tryAcquirePermission();

}
 
Example #20
Source File: TaggedBulkheadMetricsPublisherTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testReplaceNewMeter(){
    Bulkhead oldOne = Bulkhead.of("backendC", BulkheadConfig.ofDefaults());
    // add meters of old
    taggedBulkheadMetricsPublisher.addMetrics(meterRegistry, oldOne);
    // one success call
    oldOne.tryAcquirePermission();

    assertThat(taggedBulkheadMetricsPublisher.meterIdMap).containsKeys("backendC");
    assertThat(taggedBulkheadMetricsPublisher.meterIdMap.get("backendC")).hasSize(2);
    Collection<Gauge> gauges = meterRegistry
        .get(DEFAULT_BULKHEAD_MAX_ALLOWED_CONCURRENT_CALLS_METRIC_NAME).gauges();
    Optional<Gauge> successful = findMeterByNamesTag(gauges, oldOne.getName());
    assertThat(successful).isPresent();
    assertThat(successful.get().value())
        .isEqualTo(oldOne.getMetrics().getMaxAllowedConcurrentCalls());

    Bulkhead newOne = Bulkhead.of("backendC", BulkheadConfig.ofDefaults());

    // add meters of new
    taggedBulkheadMetricsPublisher.addMetrics(meterRegistry, newOne);
    // three success call
    newOne.tryAcquirePermission();
    newOne.tryAcquirePermission();
    newOne.tryAcquirePermission();

    assertThat(taggedBulkheadMetricsPublisher.meterIdMap).containsKeys("backendC");
    assertThat(taggedBulkheadMetricsPublisher.meterIdMap.get("backendC")).hasSize(2);
    gauges = meterRegistry
        .get(DEFAULT_BULKHEAD_MAX_ALLOWED_CONCURRENT_CALLS_METRIC_NAME).gauges();
    successful = findMeterByNamesTag(gauges, newOne.getName());
    assertThat(successful).isPresent();
    assertThat(successful.get().value())
        .isEqualTo(newOne.getMetrics().getMaxAllowedConcurrentCalls());

}
 
Example #21
Source File: Resilience4jModule.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Override
public BulkheadRegistry get() {
    // build configs
    BulkheadConfigurationProperties bulkheadProperties = resilience4jConfig.getBulkhead();
    Map<String, BulkheadConfig> configs = bulkheadProperties.getConfigs()
        .entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,
            entry -> bulkheadProperties.createBulkheadConfig(entry.getValue(),
                new CompositeCustomizer<BulkheadConfigCustomizer>(Collections.emptyList()),
                entry.getKey())));
    BulkheadRegistry bulkheadRegistry = BulkheadRegistry.of(configs);

    // build bulkheads
    EndpointsConfig endpointsConfig = resilience4jConfig.getEndpoints();
    bulkheadProperties.getInstances().forEach((name, bulkheadConfig) -> {
        io.github.resilience4j.bulkhead.Bulkhead bulkhead =
            bulkheadRegistry
                .bulkhead(name, bulkheadProperties.createBulkheadConfig(bulkheadConfig,
                    new CompositeCustomizer<>(Collections.emptyList()), name));
        if (endpointsConfig.getBulkhead().isEnabled()) {
            bulkhead.getEventPublisher().onEvent(eventConsumerRegistry
                .createEventConsumer(name,
                    bulkheadConfig.getEventConsumerBufferSize() != null ? bulkheadConfig
                        .getEventConsumerBufferSize() : 100));
        }
    });

    return bulkheadRegistry;
}
 
Example #22
Source File: BulkheadConfiguration.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes a bulkhead registry.
 *
 * @param bulkheadConfigurationProperties The bulkhead configuration properties.
 * @param compositeBulkheadCustomizer
 * @return a BulkheadRegistry
 */
private BulkheadRegistry createBulkheadRegistry(
    BulkheadConfigurationProperties bulkheadConfigurationProperties,
    RegistryEventConsumer<Bulkhead> bulkheadRegistryEventConsumer,
    CompositeCustomizer<BulkheadConfigCustomizer> compositeBulkheadCustomizer) {
    Map<String, BulkheadConfig> configs = bulkheadConfigurationProperties.getConfigs()
        .entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,
            entry -> bulkheadConfigurationProperties.createBulkheadConfig(entry.getValue(),
                compositeBulkheadCustomizer, entry.getKey())));
    return BulkheadRegistry.of(configs, bulkheadRegistryEventConsumer,
        io.vavr.collection.HashMap.ofAll(bulkheadConfigurationProperties.getTags()));
}
 
Example #23
Source File: TestApplication.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Bean
public BulkheadConfigCustomizer testBulkheadConfigCustomizer() {
    return new BulkheadConfigCustomizer() {
        @Override
        public void customize(BulkheadConfig.Builder configBuilder) {
            configBuilder.maxConcurrentCalls(3);
        }

        @Override
        public String name() {
            return "backendD";
        }
    };
}
 
Example #24
Source File: BulkheadConfigurationProperties.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
public BulkheadConfig createBulkheadConfig(InstanceProperties instanceProperties,
    CompositeCustomizer<BulkheadConfigCustomizer> compositeBulkheadCustomizer,
    String instanceName) {
    if (StringUtils.isNotEmpty(instanceProperties.getBaseConfig())) {
        InstanceProperties baseProperties = configs.get(instanceProperties.getBaseConfig());
        if (baseProperties == null) {
            throw new ConfigurationNotFoundException(instanceProperties.getBaseConfig());
        }
        return buildConfigFromBaseConfig(baseProperties, instanceProperties,
            compositeBulkheadCustomizer, instanceName);
    }
    return buildBulkheadConfig(BulkheadConfig.custom(), instanceProperties,
        compositeBulkheadCustomizer, instanceName);
}
 
Example #25
Source File: BulkheadConfigurationProperties.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
private BulkheadConfig buildConfigFromBaseConfig(InstanceProperties baseProperties,
    InstanceProperties instanceProperties,
    CompositeCustomizer<BulkheadConfigCustomizer> compositeBulkheadCustomizer,
    String instanceName) {
    ConfigUtils.mergePropertiesIfAny(baseProperties, instanceProperties);
    BulkheadConfig baseConfig = buildBulkheadConfig(BulkheadConfig.custom(), baseProperties,
        compositeBulkheadCustomizer, instanceName);
    return buildBulkheadConfig(BulkheadConfig.from(baseConfig), instanceProperties,
        compositeBulkheadCustomizer, instanceName);
}
 
Example #26
Source File: BulkheadConfigurationProperties.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
private BulkheadConfig buildBulkheadConfig(BulkheadConfig.Builder builder,
    InstanceProperties instanceProperties,
    CompositeCustomizer<BulkheadConfigCustomizer> compositeBulkheadCustomizer,
    String instanceName) {
    if (instanceProperties.getMaxConcurrentCalls() != null) {
        builder.maxConcurrentCalls(instanceProperties.getMaxConcurrentCalls());
    }
    if (instanceProperties.getMaxWaitDuration() != null) {
        builder.maxWaitDuration(instanceProperties.getMaxWaitDuration());
    }
    compositeBulkheadCustomizer.getCustomizer(instanceName)
        .ifPresent(bulkheadConfigCustomizer -> bulkheadConfigCustomizer.customize(builder));
    return builder.build();
}
 
Example #27
Source File: BulkheadConfigurationPropertiesTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testBulkHeadProperties() {
    //Given
    BulkheadConfigurationProperties.InstanceProperties instanceProperties1 = new BulkheadConfigurationProperties.InstanceProperties();
    instanceProperties1.setMaxConcurrentCalls(3);
    assertThat(instanceProperties1.getEventConsumerBufferSize()).isNull();

    BulkheadConfigurationProperties.InstanceProperties instanceProperties2 = new BulkheadConfigurationProperties.InstanceProperties();
    instanceProperties2.setMaxConcurrentCalls(2);
    assertThat(instanceProperties2.getEventConsumerBufferSize()).isNull();

    BulkheadConfigurationProperties bulkheadConfigurationProperties = new BulkheadConfigurationProperties();
    bulkheadConfigurationProperties.getInstances().put("backend1", instanceProperties1);
    bulkheadConfigurationProperties.getInstances().put("backend2", instanceProperties2);
    Map<String, String> globalTags = new HashMap<>();
    globalTags.put("testKey1", "testKet2");
    bulkheadConfigurationProperties.setTags(globalTags);
    //Then
    assertThat(bulkheadConfigurationProperties.getInstances().size()).isEqualTo(2);
    assertThat(bulkheadConfigurationProperties.getTags()).isNotEmpty();
    BulkheadConfig bulkhead1 = bulkheadConfigurationProperties
        .createBulkheadConfig(instanceProperties1, compositeBulkheadCustomizer(), "backend1");
    assertThat(bulkhead1).isNotNull();
    assertThat(bulkhead1.getMaxConcurrentCalls()).isEqualTo(3);

    BulkheadConfig bulkhead2 = bulkheadConfigurationProperties
        .createBulkheadConfig(instanceProperties2, compositeBulkheadCustomizer(), "backend2");
    assertThat(bulkhead2).isNotNull();
    assertThat(bulkhead2.getMaxConcurrentCalls()).isEqualTo(2);


}
 
Example #28
Source File: BulkheadMetricsPublisherTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Override
protected Bulkhead givenMetricRegistry(String prefix, MetricRegistry metricRegistry) {
    BulkheadRegistry bulkheadRegistry =
        BulkheadRegistry.of(BulkheadConfig.ofDefaults(),
            new BulkheadMetricsPublisher(prefix, metricRegistry));

    return bulkheadRegistry.bulkhead("testBulkhead");
}
 
Example #29
Source File: BulkheadMetricsPublisherTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Override
protected Bulkhead givenMetricRegistry(MetricRegistry metricRegistry) {
    BulkheadRegistry bulkheadRegistry = BulkheadRegistry
        .of(BulkheadConfig.ofDefaults(), new BulkheadMetricsPublisher(metricRegistry));

    return bulkheadRegistry.bulkhead("testBulkhead");
}
 
Example #30
Source File: Resilience4jUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenBulkheadIsUsed_thenItWorksAsExpected() throws InterruptedException {
    BulkheadConfig config = BulkheadConfig.custom().maxConcurrentCalls(1).build();
    BulkheadRegistry registry = BulkheadRegistry.of(config);
    Bulkhead bulkhead = registry.bulkhead("my");
    Function<Integer, Integer> decorated = Bulkhead.decorateFunction(bulkhead, service::process);

    Future<?> taskInProgress = callAndBlock(decorated);
    try {
        assertThat(bulkhead.isCallPermitted()).isFalse();
    } finally {
        taskInProgress.cancel(true);
    }
}