Java Code Examples for io.github.resilience4j.retry.RetryRegistry#of()
The following examples show how to use
io.github.resilience4j.retry.RetryRegistry#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: 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 2
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 3
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 4
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 5
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 6
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 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: TaggedRetryMetricsPublisherTest.java From resilience4j with Apache License 2.0 | 5 votes |
@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 11
Source File: Resilience4jModule.java From resilience4j with Apache License 2.0 | 5 votes |
@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 12
Source File: RetryConfiguration.java From resilience4j with Apache License 2.0 | 5 votes |
/** * 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: 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; }