io.github.resilience4j.retry.RetryRegistry Java Examples

The following examples show how to use io.github.resilience4j.retry.RetryRegistry. 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: PublicAccessAutoFix.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
   * Gets the instance details for ec 2.
   *
   * @param clientMap the client map
   * @param resourceId the resource id
   * @return the instance details for ec 2
   * @throws Exception the exception
   */
  public static Instance getInstanceDetailsForEc2(Map<String,Object> clientMap,String resourceId) throws Exception {
  	AmazonEC2 ec2Client = (AmazonEC2) clientMap.get("client");
  	DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
describeInstancesRequest.setInstanceIds(Arrays.asList(resourceId));


RetryConfig config = RetryConfig.custom().maxAttempts(MAX_ATTEMPTS).waitDuration(Duration.ofSeconds(WAIT_INTERVAL)).build();
RetryRegistry registry = RetryRegistry.of(config);

Retry retry = registry.retry(describeInstancesRequest.toString());
 		
Function<Integer, Instance> decorated
  =  Retry.decorateFunction(retry, (Integer s) -> {
	  DescribeInstancesResult  describeInstancesResult =  ec2Client.describeInstances(describeInstancesRequest);
	  List<Reservation> reservations = describeInstancesResult.getReservations();
		Reservation reservation = reservations.get(0);
		List<Instance> instances = reservation.getInstances();
		return instances.get(0);
    });
return decorated.apply(1);
	
  }
 
Example #2
Source File: Resilience4jUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenRetryIsUsed_thenItWorksAsExpected() {
    RetryConfig config = RetryConfig.custom().maxAttempts(2).build();
    RetryRegistry registry = RetryRegistry.of(config);
    Retry retry = registry.retry("my");
    Function<Integer, Void> decorated = Retry.decorateFunction(retry, (Integer s) -> {
        service.process(s);
        return null;
    });

    when(service.process(anyInt())).thenThrow(new RuntimeException());
    try {
        decorated.apply(1);
        fail("Expected an exception to be thrown if all retries failed");
    } catch (Exception e) {
        verify(service, times(2)).process(any(Integer.class));
    }
}
 
Example #3
Source File: SpringBootCommonTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testRetryCommonConfig() {
    RetryConfigurationOnMissingBean retryConfigurationOnMissingBean = new RetryConfigurationOnMissingBean();
    assertThat(retryConfigurationOnMissingBean.reactorRetryAspectExt()).isNotNull();
    assertThat(retryConfigurationOnMissingBean.rxJava2RetryAspectExt()).isNotNull();
    assertThat(retryConfigurationOnMissingBean
        .retryRegistry(new RetryConfigurationProperties(), new DefaultEventConsumerRegistry<>(),
            new CompositeRegistryEventConsumer<>(Collections.emptyList()),
            new CompositeCustomizer<>(Collections.emptyList()))).isNotNull();
    assertThat(retryConfigurationOnMissingBean
        .retryAspect(new RetryConfigurationProperties(), RetryRegistry.ofDefaults(),
            Collections.emptyList(),
            new FallbackDecorators(Arrays.asList(new CompletionStageFallbackDecorator())),
            new SpelResolver(new SpelExpressionParser(), new StandardReflectionParameterNameDiscoverer()))).isNotNull();
    assertThat(retryConfigurationOnMissingBean.retryRegistryEventConsumer(Optional.empty())).isNotNull();
}
 
Example #4
Source File: TaggedRetryMetricsTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void metricsAreRegisteredWithCustomNames() {
    MeterRegistry meterRegistry = new SimpleMeterRegistry();
    RetryRegistry retryRegistry = RetryRegistry.ofDefaults();
    retryRegistry.retry("backendA");
    TaggedRetryMetrics.ofRetryRegistry(
        RetryMetricNames.custom()
            .callsMetricName("custom_calls")
            .build(),
        retryRegistry
    ).bindTo(meterRegistry);

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

    assertThat(metricNames).hasSameElementsAs(Collections.singletonList("custom_calls"));
}
 
Example #5
Source File: TaggedRetryMetricsPublisherTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void metricsAreRegisteredWithCustomNames() {
    MeterRegistry meterRegistry = new SimpleMeterRegistry();
    TaggedRetryMetricsPublisher taggedRetryMetricsPublisher = new TaggedRetryMetricsPublisher(
        RetryMetricNames.custom()
            .callsMetricName("custom_calls")
            .build(), meterRegistry);
    RetryRegistry retryRegistry = RetryRegistry
        .of(RetryConfig.ofDefaults(), taggedRetryMetricsPublisher);
    retryRegistry.retry("backendA");

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

    assertThat(metricNames).hasSameElementsAs(Collections.singletonList("custom_calls"));
}
 
Example #6
Source File: RetryMetricsCollectorTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
    registry = new CollectorRegistry();
    retryRegistry = RetryRegistry.ofDefaults();
    retry = retryRegistry.retry("backendA");

    RetryMetricsCollector.ofRetryRegistry(retryRegistry).register(registry);

    retry.executeSupplier(() -> "return");

    Supplier<String> supplier = Retry.decorateSupplier(retry, () -> {
        throw new RuntimeException();
    });

    Try.ofSupplier(supplier);
}
 
Example #7
Source File: ExampleIntegrationTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void helloHttp_shouldRunWithFunctionsFramework() throws Throwable {
  String functionUrl = BASE_URL + "/helloHttp";

  HttpRequest getRequest = HttpRequest.newBuilder().uri(URI.create(functionUrl)).GET().build();

  // The Functions Framework Maven plugin process takes time to start up
  // Use resilience4j to retry the test HTTP request until the plugin responds
  RetryRegistry registry = RetryRegistry.of(RetryConfig.custom()
      .maxAttempts(8)
      .intervalFunction(IntervalFunction.ofExponentialBackoff(200, 2))
      .retryExceptions(IOException.class)
      .build());
  Retry retry = registry.retry("my");

  // Perform the request-retry process
  String body = Retry.decorateCheckedSupplier(retry, () -> client.send(
      getRequest,
      HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)).body()
  ).apply();

  // Verify the function returned the right results
  assertThat(body).isEqualTo("Hello world!");
}
 
Example #8
Source File: BackendBController.java    From resilience4j-spring-boot2-demo with Apache License 2.0 6 votes vote down vote up
public BackendBController(
        @Qualifier("backendBService")Service businessBService,
        CircuitBreakerRegistry circuitBreakerRegistry,
        ThreadPoolBulkheadRegistry threadPoolBulkheadRegistry,
        BulkheadRegistry bulkheadRegistry,
        RetryRegistry retryRegistry,
        RateLimiterRegistry rateLimiterRegistry,
        TimeLimiterRegistry timeLimiterRegistry){
    this.businessBService = businessBService;
    this.circuitBreaker = circuitBreakerRegistry.circuitBreaker(BACKEND_B);
    this.bulkhead = bulkheadRegistry.bulkhead(BACKEND_B);
    this.threadPoolBulkhead = threadPoolBulkheadRegistry.bulkhead(BACKEND_B);
    this.retry = retryRegistry.retry(BACKEND_B);
    this.rateLimiter = rateLimiterRegistry.rateLimiter(BACKEND_B);
    this.timeLimiter = timeLimiterRegistry.timeLimiter(BACKEND_B);
    this.scheduledExecutorService = Executors.newScheduledThreadPool(3);
}
 
Example #9
Source File: AbstractRetryConfigurationOnMissingBean.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
/**
 * @param retryConfigurationProperties retry configuration spring properties
 * @param retryRegistry                retry in memory registry
 * @return the spring retry AOP aspect
 */
@Bean
@Conditional(value = {AspectJOnClasspathCondition.class})
@ConditionalOnMissingBean
public RetryAspect retryAspect(
    RetryConfigurationProperties retryConfigurationProperties,
    RetryRegistry retryRegistry,
    @Autowired(required = false) List<RetryAspectExt> retryAspectExtList,
    FallbackDecorators fallbackDecorators,
    SpelResolver spelResolver
) {
    return retryConfiguration
        .retryAspect(retryConfigurationProperties, retryRegistry, retryAspectExtList,
            fallbackDecorators, spelResolver);
}
 
Example #10
Source File: Resilience4jModule.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Override
public RetryRegistry get() {
    // build configs
    RetryConfigurationProperties RetryProperties = resilience4jConfig.getRetry();
    Map<String, RetryConfig> configs = RetryProperties.getConfigs()
        .entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,
            entry -> RetryProperties.createRetryConfig(entry.getValue(),
                new CompositeCustomizer<RetryConfigCustomizer>(Collections.emptyList()),
                entry.getKey())));
    RetryRegistry retryRegistry = RetryRegistry.of(configs);

    // build retries
    EndpointsConfig endpointsConfig = resilience4jConfig.getEndpoints();
    RetryProperties.getInstances().forEach((name, retryConfig) -> {
        io.github.resilience4j.retry.Retry retry =
            retryRegistry.retry(name, RetryProperties.createRetryConfig(retryConfig,
                new CompositeCustomizer<>(Collections.emptyList()), name));
        if (endpointsConfig.getRetry().isEnabled()) {
            retry.getEventPublisher().onEvent(eventConsumerRegistry
                .createEventConsumer(name,
                    retryConfig.getEventConsumerBufferSize() != null ? retryConfig
                        .getEventConsumerBufferSize() : 100));
        }
    });

    return retryRegistry;
}
 
Example #11
Source File: RetryAspect.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
/**
 * @param retryConfigurationProperties spring retry config properties
 * @param retryRegistry                retry definition registry
 * @param retryAspectExtList           a list of retry aspect extensions
 * @param fallbackDecorators           the fallback decorators
 * @param spelResolver                 spel expression parser
 */
public RetryAspect(RetryConfigurationProperties retryConfigurationProperties,
                   RetryRegistry retryRegistry,
                   @Autowired(required = false) List<RetryAspectExt> retryAspectExtList,
                   FallbackDecorators fallbackDecorators,
                   SpelResolver spelResolver) {
    this.retryConfigurationProperties = retryConfigurationProperties;
    this.retryRegistry = retryRegistry;
    this.retryAspectExtList = retryAspectExtList;
    this.fallbackDecorators = fallbackDecorators;
    this.spelResolver = spelResolver;
}
 
Example #12
Source File: RetryConfiguration.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes a retry registry.
 *
 * @param retryConfigurationProperties The retry configuration properties.
 * @return a RetryRegistry
 */
private RetryRegistry createRetryRegistry(
    RetryConfigurationProperties retryConfigurationProperties,
    RegistryEventConsumer<Retry> retryRegistryEventConsumer,
    CompositeCustomizer<RetryConfigCustomizer> compositeRetryCustomizer) {
    Map<String, RetryConfig> configs = retryConfigurationProperties.getConfigs()
        .entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,
            entry -> retryConfigurationProperties
                .createRetryConfig(entry.getValue(), compositeRetryCustomizer,
                    entry.getKey())));

    return RetryRegistry.of(configs, retryRegistryEventConsumer,
        io.vavr.collection.HashMap.ofAll(retryConfigurationProperties.getTags()));
}
 
Example #13
Source File: ExampleSystemTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void helloPubSub_shouldRunOnGcf() throws Exception {
  String name = UUID.randomUUID().toString();

  // Subtract time to work-around local-GCF clock difference
  Instant startInstant = Instant.now().minus(Duration.ofMinutes(4));
  String startTimestamp = DateTimeFormatter.ISO_INSTANT.format(startInstant);

  // Publish to pub/sub topic
  ByteString byteStr = ByteString.copyFrom(name, StandardCharsets.UTF_8);
  PubsubMessage pubsubApiMessage = PubsubMessage.newBuilder().setData(byteStr).build();
  publisher.publish(pubsubApiMessage).get();

  // Keep retrying until the logs contain the desired invocation's log entry
  // (If the invocation failed, the retry process will eventually time out)
  RetryRegistry registry = RetryRegistry.of(RetryConfig.custom()
      .maxAttempts(8)
      .intervalFunction(IntervalFunction.ofExponentialBackoff(1000, 2))
      .retryOnResult(s -> !s.toString().contains(name))
      .build());
  Retry retry = registry.retry(name);
  String logEntry = Retry
      .decorateFunction(retry, ExampleSystemTest::getLogEntriesAsString)
      .apply(startTimestamp);

  // Perform final assertion (to make sure we fail on timeout)
  assertThat(logEntry).contains(name);
}
 
Example #14
Source File: RetryConfiguration.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
/**
 * @param retryConfigurationProperties retry configuration spring properties
 * @param retryRegistry                retry in memory registry
 * @return the spring retry AOP aspect
 */
@Bean
@Conditional(value = {AspectJOnClasspathCondition.class})
public RetryAspect retryAspect(
    RetryConfigurationProperties retryConfigurationProperties,
    RetryRegistry retryRegistry,
    @Autowired(required = false) List<RetryAspectExt> retryAspectExtList,
    FallbackDecorators fallbackDecorators,
    SpelResolver spelResolver
) {
    return new RetryAspect(retryConfigurationProperties, retryRegistry, retryAspectExtList,
        fallbackDecorators, spelResolver);
}
 
Example #15
Source File: RetryConfigurationSpringTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Bean
public RetryAspect retryAspect(
    RetryRegistry retryRegistry,
    @Autowired(required = false) List<RetryAspectExt> retryAspectExts,
    FallbackDecorators fallbackDecorators,
    SpelResolver spelResolver
) {
    retryAspect = new RetryAspect(retryConfigurationProperties(), retryRegistry,
        retryAspectExts, fallbackDecorators, spelResolver);
    return retryAspect;
}
 
Example #16
Source File: RetryConfigurationTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testRetryRegistry() {
    InstanceProperties instanceProperties1 = new InstanceProperties();
    instanceProperties1.setMaxRetryAttempts(3);
    InstanceProperties instanceProperties2 = new InstanceProperties();
    instanceProperties2.setMaxRetryAttempts(2);
    RetryConfigurationProperties retryConfigurationProperties = new RetryConfigurationProperties();
    retryConfigurationProperties.getInstances().put("backend1", instanceProperties1);
    retryConfigurationProperties.getInstances().put("backend2", instanceProperties2);
    retryConfigurationProperties.setRetryAspectOrder(200);
    RetryConfiguration retryConfiguration = new RetryConfiguration();
    DefaultEventConsumerRegistry<RetryEvent> eventConsumerRegistry = new DefaultEventConsumerRegistry<>();

    RetryRegistry retryRegistry = retryConfiguration
        .retryRegistry(retryConfigurationProperties, eventConsumerRegistry,
            new CompositeRegistryEventConsumer<>(emptyList()), compositeRetryCustomizerTest());

    assertThat(retryConfigurationProperties.getRetryAspectOrder()).isEqualTo(200);
    assertThat(retryRegistry.getAllRetries().size()).isEqualTo(2);
    Retry retry1 = retryRegistry.retry("backend1");
    assertThat(retry1).isNotNull();
    assertThat(retry1.getRetryConfig().getMaxAttempts()).isEqualTo(3);
    Retry retry2 = retryRegistry.retry("backend2");
    assertThat(retry2).isNotNull();
    assertThat(retry2.getRetryConfig().getMaxAttempts()).isEqualTo(2);
    assertThat(eventConsumerRegistry.getAllEventConsumer()).hasSize(2);
}
 
Example #17
Source File: AbstractRetryConfigurationOnMissingBean.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
/**
 * @param retryConfigurationProperties retryConfigurationProperties retry configuration spring
 *                                     properties
 * @param retryEventConsumerRegistry   the event retry registry
 * @return the retry definition registry
 */
@Bean
@ConditionalOnMissingBean
public RetryRegistry retryRegistry(RetryConfigurationProperties retryConfigurationProperties,
    EventConsumerRegistry<RetryEvent> retryEventConsumerRegistry,
    RegistryEventConsumer<Retry> retryRegistryEventConsumer,
    @Qualifier("compositeRetryCustomizer") CompositeCustomizer<RetryConfigCustomizer> compositeRetryCustomizer) {
    return retryConfiguration
        .retryRegistry(retryConfigurationProperties, retryEventConsumerRegistry,
            retryRegistryEventConsumer, compositeRetryCustomizer);
}
 
Example #18
Source File: RetryConfiguration.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
/**
 * Registers the post creation consumer function that registers the consumer events to the
 * retries.
 *
 * @param retryRegistry         The retry registry.
 * @param eventConsumerRegistry The event consumer registry.
 */
private void registerEventConsumer(RetryRegistry retryRegistry,
    EventConsumerRegistry<RetryEvent> eventConsumerRegistry,
    RetryConfigurationProperties retryConfigurationProperties) {
    retryRegistry.getEventPublisher().onEntryAdded(
        event -> registerEventConsumer(eventConsumerRegistry, event.getAddedEntry(),
            retryConfigurationProperties));
}
 
Example #19
Source File: RetryConfigurationOnMissingBeanTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Bean
public RetryAspect retryAspect(
    RetryRegistry retryRegistry,
    @Autowired(required = false) List<RetryAspectExt> retryAspectExts,
    FallbackDecorators fallbackDecorators,
    SpelResolver spelResolver
) {
    this.retryAspect = new RetryAspect(new RetryProperties(), retryRegistry,
        retryAspectExts, fallbackDecorators, spelResolver);
    return retryAspect;
}
 
Example #20
Source File: RetryMetricsPublisherTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Override
protected Retry givenMetricRegistry(String prefix, MetricRegistry metricRegistry) {
    RetryRegistry retryRegistry = RetryRegistry
        .of(RetryConfig.ofDefaults(), new RetryMetricsPublisher(prefix, metricRegistry));

    return retryRegistry.retry("testName");
}
 
Example #21
Source File: RetryMetricsPublisherTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Override
protected Retry givenMetricRegistry(MetricRegistry metricRegistry) {
    RetryRegistry retryRegistry = RetryRegistry
        .of(RetryConfig.ofDefaults(), new RetryMetricsPublisher(metricRegistry));

    return retryRegistry.retry("testName");
}
 
Example #22
Source File: RetryMetricsTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Override
protected Retry givenMetricRegistry(String prefix, MetricRegistry metricRegistry) {
    RetryRegistry retryRegistry = RetryRegistry
        .of(RetryConfig.custom().waitDuration(Duration.ofMillis(150)).build());
    Retry retry = retryRegistry.retry("testName");
    metricRegistry.registerAll(RetryMetrics.ofRetryRegistry(prefix, retryRegistry));

    return retry;
}
 
Example #23
Source File: RetryMetricsTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Override
protected Retry givenMetricRegistry(MetricRegistry metricRegistry) {
    RetryRegistry retryRegistry = RetryRegistry
        .of(RetryConfig.custom().waitDuration(Duration.ofMillis(150)).build());
    Retry retry = retryRegistry.retry("testName");
    metricRegistry.registerAll(RetryMetrics.ofRetryRegistry(retryRegistry));

    return retry;
}
 
Example #24
Source File: PublicAccessAutoFix.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the existing security group details.
 *
 * @param securityGroupList the security group list
 * @param ec2Client the ec 2 client
 * @return the existing security group details
 */
public static List<SecurityGroup> getExistingSecurityGroupDetails(Set<String> securityGroupList, AmazonEC2 ec2Client) {
	RetryConfig config = RetryConfig.custom().maxAttempts(MAX_ATTEMPTS).waitDuration(Duration.ofSeconds(WAIT_INTERVAL)).build();
	RetryRegistry registry = RetryRegistry.of(config);
	DescribeSecurityGroupsRequest securityGroups = new DescribeSecurityGroupsRequest();
  		securityGroups.setGroupIds(securityGroupList);
	Retry retry = registry.retry(securityGroups.toString());
  		
	Function<Integer, List<SecurityGroup>> decorated
	  =  Retry.decorateFunction(retry, (Integer s) -> {
		  DescribeSecurityGroupsResult  groupsResult =  ec2Client.describeSecurityGroups(securityGroups);
		  return groupsResult.getSecurityGroups();
	    });
	return decorated.apply(1);
}
 
Example #25
Source File: ExampleIntegrationTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void helloGcs_shouldRunWithFunctionsFramework() throws Throwable {
  String functionUrl = BASE_URL + "/helloGcs"; // URL to your locally-running function

  // Initialize constants
  String name = UUID.randomUUID().toString();
  String jsonStr = gson.toJson(Map.of(
      "data", Map.of(
          "name", name, "resourceState", "exists", "metageneration", 1),
      "context", Map.of(
          "eventType", "google.storage.object.finalize")
  ));

  HttpPost postRequest =  new HttpPost(URI.create(functionUrl));
  postRequest.setEntity(new StringEntity(jsonStr));

  // The Functions Framework Maven plugin process takes time to start up
  // Use resilience4j to retry the test HTTP request until the plugin responds
  RetryRegistry registry = RetryRegistry.of(RetryConfig.custom()
      .maxAttempts(8)
      .retryExceptions(HttpHostConnectException.class)
      .intervalFunction(IntervalFunction.ofExponentialBackoff(200, 2))
      .build());
  Retry retry = registry.retry("my");

  // Perform the request-retry process
  CheckedRunnable retriableFunc = Retry.decorateCheckedRunnable(
      retry, () -> client.execute(postRequest));
  retriableFunc.run();

  // Get Functions Framework plugin process' stdout
  InputStream stdoutStream = emulatorProcess.getErrorStream();
  ByteArrayOutputStream stdoutBytes = new ByteArrayOutputStream();
  stdoutBytes.write(stdoutStream.readNBytes(stdoutStream.available()));

  // Verify desired name value is present
  assertThat(stdoutBytes.toString(StandardCharsets.UTF_8)).contains(
      String.format("File %s uploaded.", name));
}
 
Example #26
Source File: ExampleSystemTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void helloGcs_shouldRunOnGcf() {
  String filename = String.format("test-%s.txt", UUID.randomUUID());

  // Subtract time to work-around local-GCF clock difference
  Instant startInstant = Instant.now().minus(Duration.ofMinutes(4));
  String startTimestamp = DateTimeFormatter.ISO_INSTANT.format(startInstant);

  // Upload a file to Cloud Storage
  BlobInfo blobInfo = BlobInfo.newBuilder(BlobId.of(FUNCTIONS_BUCKET, filename)).build();
  STORAGE.create(blobInfo);

  // Keep retrying until the logs contain the desired invocation's log entry
  // (If the invocation failed, the retry process will eventually time out)
  String expected = String.format("File %s uploaded.", filename);
  RetryRegistry registry = RetryRegistry.of(RetryConfig.custom()
      .maxAttempts(8)
      .intervalFunction(IntervalFunction.ofExponentialBackoff(1000, 2))
      .retryOnResult(s -> !s.toString().contains(expected))
      .build());
  Retry retry = registry.retry(filename);
  String logEntry = Retry
      .decorateFunction(retry, ExampleSystemTest::getLogEntriesAsString)
      .apply(startTimestamp);

  // Perform final assertion (to make sure we fail on timeout)
  assertThat(logEntry).contains(filename);
}
 
Example #27
Source File: TaggedRetryMetricsTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    meterRegistry = new SimpleMeterRegistry();
    retryRegistry = RetryRegistry.ofDefaults();

    retry = retryRegistry.retry("backendA");
    // record some basic stats
    retry.executeRunnable(() -> {
    });

    taggedRetryMetrics = TaggedRetryMetrics.ofRetryRegistry(retryRegistry);
    taggedRetryMetrics.bindTo(meterRegistry);
}
 
Example #28
Source File: ExampleIntegrationTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void helloPubSub_shouldRunWithFunctionsFramework() throws Throwable {
  String functionUrl = BASE_URL + "/helloPubsub"; // URL to your locally-running function

  // Initialize constants
  String name = UUID.randomUUID().toString();
  String nameBase64 = Base64.getEncoder().encodeToString(name.getBytes(StandardCharsets.UTF_8));

  String jsonStr = gson.toJson(Map.of("data", Map.of("data", nameBase64)));

  HttpPost postRequest =  new HttpPost(URI.create(functionUrl));
  postRequest.setEntity(new StringEntity(jsonStr));

  // The Functions Framework Maven plugin process takes time to start up
  // Use resilience4j to retry the test HTTP request until the plugin responds
  RetryRegistry registry = RetryRegistry.of(RetryConfig.custom()
      .maxAttempts(8)
      .retryExceptions(HttpHostConnectException.class)
      .intervalFunction(IntervalFunction.ofExponentialBackoff(200, 2))
      .build());
  Retry retry = registry.retry("my");

  // Perform the request-retry process
  CheckedRunnable retriableFunc = Retry.decorateCheckedRunnable(
      retry, () -> client.execute(postRequest));
  retriableFunc.run();

  // Get Functions Framework plugin process' stdout
  InputStream stdoutStream = emulatorProcess.getErrorStream();
  ByteArrayOutputStream stdoutBytes = new ByteArrayOutputStream();
  stdoutBytes.write(stdoutStream.readNBytes(stdoutStream.available()));

  // Verify desired name value is present
  assertThat(stdoutBytes.toString(StandardCharsets.UTF_8)).contains(
      String.format("Hello %s!", name));
}
 
Example #29
Source File: TaggedRetryMetricsPublisherTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    meterRegistry = new SimpleMeterRegistry();
    taggedRetryMetricsPublisher = new TaggedRetryMetricsPublisher(meterRegistry);
    retryRegistry = RetryRegistry.of(RetryConfig.ofDefaults(), taggedRetryMetricsPublisher);

    retry = retryRegistry.retry("backendA");
    // record some basic stats
    retry.executeRunnable(() -> {
    });
}
 
Example #30
Source File: RefreshScopedRetryAutoConfiguration.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
/**
 * @param retryConfigurationProperties retry spring configuration properties
 * @param retryEventConsumerRegistry   the retry event consumer registry
 * @return the RefreshScoped RetryRegistry
 */
@Bean
@org.springframework.cloud.context.config.annotation.RefreshScope
@ConditionalOnMissingBean
public RetryRegistry retryRegistry(RetryConfigurationProperties retryConfigurationProperties,
                                   EventConsumerRegistry<RetryEvent> retryEventConsumerRegistry,
                                   RegistryEventConsumer<Retry> retryRegistryEventConsumer,
                                   @Qualifier("compositeRetryCustomizer") CompositeCustomizer<RetryConfigCustomizer> compositeRetryCustomizer) {
    return retryConfiguration
        .retryRegistry(retryConfigurationProperties, retryEventConsumerRegistry,
            retryRegistryEventConsumer, compositeRetryCustomizer);
}