Java Code Examples for io.github.resilience4j.retry.RetryRegistry#retry()
The following examples show how to use
io.github.resilience4j.retry.RetryRegistry#retry() .
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: TaggedRetryMetricsPublisherTest.java From resilience4j with Apache License 2.0 | 6 votes |
@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 2
Source File: Resilience4jUnitTest.java From tutorials with MIT License | 6 votes |
@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: TaggedRetryMetricsTest.java From resilience4j with Apache License 2.0 | 6 votes |
@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 4
Source File: ExampleIntegrationTest.java From java-docs-samples with Apache License 2.0 | 6 votes |
@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 5
Source File: BackendBController.java From resilience4j-spring-boot2-demo with Apache License 2.0 | 6 votes |
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 6
Source File: PublicAccessAutoFix.java From pacbot with Apache License 2.0 | 6 votes |
/** * 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 7
Source File: ExampleSystemTest.java From java-docs-samples with Apache License 2.0 | 5 votes |
@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 8
Source File: ExampleIntegrationTest.java From java-docs-samples with Apache License 2.0 | 5 votes |
@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 9
Source File: ExampleSystemTest.java From java-docs-samples with Apache License 2.0 | 5 votes |
@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 10
Source File: ExampleIntegrationTest.java From java-docs-samples with Apache License 2.0 | 5 votes |
@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 11
Source File: PublicAccessAutoFix.java From pacbot with Apache License 2.0 | 5 votes |
/** * 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 12
Source File: RetryConfigurationTest.java From resilience4j with Apache License 2.0 | 5 votes |
@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 13
Source File: RetryMetricsPublisherTest.java From resilience4j with Apache License 2.0 | 5 votes |
@Override protected Retry givenMetricRegistry(String prefix, MetricRegistry metricRegistry) { RetryRegistry retryRegistry = RetryRegistry .of(RetryConfig.ofDefaults(), new RetryMetricsPublisher(prefix, metricRegistry)); return retryRegistry.retry("testName"); }
Example 14
Source File: RetryMetricsPublisherTest.java From resilience4j with Apache License 2.0 | 5 votes |
@Override protected Retry givenMetricRegistry(MetricRegistry metricRegistry) { RetryRegistry retryRegistry = RetryRegistry .of(RetryConfig.ofDefaults(), new RetryMetricsPublisher(metricRegistry)); return retryRegistry.retry("testName"); }
Example 15
Source File: RetryMetricsTest.java From resilience4j with Apache License 2.0 | 5 votes |
@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 16
Source File: RetryMetricsTest.java From resilience4j with Apache License 2.0 | 5 votes |
@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 17
Source File: RetryConfigurationTest.java From resilience4j with Apache License 2.0 | 4 votes |
@Test public void testCreateRetryRegistryWithSharedConfigs() { InstanceProperties defaultProperties = new InstanceProperties(); defaultProperties.setMaxRetryAttempts(3); defaultProperties.setWaitDuration(Duration.ofMillis(100L)); InstanceProperties sharedProperties = new InstanceProperties(); sharedProperties.setMaxRetryAttempts(2); sharedProperties.setWaitDuration(Duration.ofMillis(100L)); InstanceProperties backendWithDefaultConfig = new InstanceProperties(); backendWithDefaultConfig.setBaseConfig("default"); backendWithDefaultConfig.setWaitDuration(Duration.ofMillis(200L)); InstanceProperties backendWithSharedConfig = new InstanceProperties(); backendWithSharedConfig.setBaseConfig("sharedConfig"); backendWithSharedConfig.setWaitDuration(Duration.ofMillis(300L)); RetryConfigurationProperties retryConfigurationProperties = new RetryConfigurationProperties(); retryConfigurationProperties.getConfigs().put("default", defaultProperties); retryConfigurationProperties.getConfigs().put("sharedConfig", sharedProperties); retryConfigurationProperties.getInstances() .put("backendWithDefaultConfig", backendWithDefaultConfig); retryConfigurationProperties.getInstances() .put("backendWithSharedConfig", backendWithSharedConfig); RetryConfiguration retryConfiguration = new RetryConfiguration(); DefaultEventConsumerRegistry<RetryEvent> eventConsumerRegistry = new DefaultEventConsumerRegistry<>(); RetryRegistry retryRegistry = retryConfiguration .retryRegistry(retryConfigurationProperties, eventConsumerRegistry, new CompositeRegistryEventConsumer<>(emptyList()), compositeRetryCustomizerTest()); assertThat(retryRegistry.getAllRetries().size()).isEqualTo(2); // Should get default config and overwrite max attempt and wait time Retry retry1 = retryRegistry.retry("backendWithDefaultConfig"); assertThat(retry1).isNotNull(); assertThat(retry1.getRetryConfig().getMaxAttempts()).isEqualTo(3); assertThat(retry1.getRetryConfig().getIntervalFunction().apply(1)).isEqualTo(200L); // Should get shared config and overwrite wait time Retry retry2 = retryRegistry.retry("backendWithSharedConfig"); assertThat(retry2).isNotNull(); assertThat(retry2.getRetryConfig().getMaxAttempts()).isEqualTo(2); assertThat(retry2.getRetryConfig().getIntervalFunction().apply(1)).isEqualTo(300L); // Unknown backend should get default config of Registry Retry retry3 = retryRegistry.retry("unknownBackend"); assertThat(retry3).isNotNull(); assertThat(retry3.getRetryConfig().getMaxAttempts()).isEqualTo(3); assertThat(eventConsumerRegistry.getAllEventConsumer()).hasSize(3); }