### Implement Basic RetryTemplate Usage Source: https://github.com/spring-projects/spring-retry/blob/main/README.md This example demonstrates the basic usage of `RetryTemplate` to execute a potentially failing operation. It configures a `TimeoutRetryPolicy` and wraps the business logic within a `RetryCallback`. ```java RetryTemplate template = new RetryTemplate(); TimeoutRetryPolicy policy = new TimeoutRetryPolicy(); policy.setTimeout(30000L); template.setRetryPolicy(policy); MyObject result = template.execute(new RetryCallback() { public MyObject doWithRetry(RetryContext context) { // Do stuff that might fail, e.g. webservice operation return result; } }); ``` -------------------------------- ### Implement Declarative Retry with Spring Retry Source: https://github.com/spring-projects/spring-retry/blob/main/README.md This Java example demonstrates the declarative approach to Spring Retry using @EnableRetry and @Retryable annotations. It shows how to configure a service method to automatically retry on specific exceptions and define a @Recover method for fallback logic after retries are exhausted. ```java @Configuration @EnableRetry public class Application { } @Service class Service { @Retryable(retryFor = RemoteAccessException.class) public void service() { // ... do something } @Recover public void recover(RemoteAccessException e) { // ... panic } } ``` -------------------------------- ### Implement Imperative Retry with Spring RetryTemplate Source: https://github.com/spring-projects/spring-retry/blob/main/README.md This Java example illustrates the imperative retry approach using RetryTemplate.builder(). It configures a retry template with a maximum number of attempts, a fixed backoff period, and specifies the exception type to retry on, then executes a block of code within the template. ```java RetryTemplate template = RetryTemplate.builder() .maxAttempts(3) .fixedBackoff(1000) .retryOn(RemoteAccessException.class) .build(); template.execute(ctx -> { // ... do something }); ``` -------------------------------- ### Implement Conditional Retry Logic with Expressions Source: https://github.com/spring-projects/spring-retry/blob/main/README.md Provides an example of using a conditional SpEL expression for maxAttemptsExpression based on method arguments. This allows the number of retry attempts to vary dynamically depending on the input parameters of the retried method. ```Java @Retryable(maxAttemptsExpression = "args[0] == 'something' ? 3 : 1") public void conditional(String string) { ... } ``` -------------------------------- ### Configure Declarative Retry with Spring AOP XML Source: https://github.com/spring-projects/spring-retry/blob/main/README.md This XML configuration snippet demonstrates how to set up declarative retry using Spring AOP. It defines a pointcut to target specific service methods (`remoteCall`) and associates it with a `RetryOperationsInterceptor` to apply retry logic. This setup uses a default `RetryTemplate` within the interceptor. ```xml ``` -------------------------------- ### Define Spring Retry Exception Classification and Recovery Source: https://github.com/spring-projects/spring-retry/blob/main/README.md Illustrates the use of retryFor, noRetryFor, and notRecoverable properties within the @Retryable annotation for fine-grained control over exception handling. It also shows an example of a @Recover method to handle exceptions after retries are exhausted or skipped. ```Java @Retryable(retryFor = RuntimeException.class, noRetryFor = IllegalStateException.class, notRecoverable = { IllegalArgumentException.class, IllegalStateException.class }) public void service() { ... } @Recover public void recover(Throwable cause) { ... } ``` -------------------------------- ### Customizing Retry and Backoff Policies with @Retryable Source: https://github.com/spring-projects/spring-retry/blob/main/README.md Illustrates how to configure `maxAttempts` and `backoff` attributes within the `@Retryable` annotation. This example sets a maximum of 12 attempts and a random backoff delay between 100 and 500 milliseconds. It also mentions the `stateful` attribute for managing retry state. ```Java @Service class Service { @Retryable(maxAttempts=12, backoff=@Backoff(delay=100, maxDelay=500)) public service() { // ... do something } } ``` -------------------------------- ### Define BackoffPolicy Interface in Spring Retry Source: https://github.com/spring-projects/spring-retry/blob/main/README.md This Java interface definition outlines the contract for `BackoffPolicy` in Spring Retry. Implementations of this interface are responsible for pausing execution between retry attempts. It includes methods to `start` a backoff context and `backOff` for the actual delay, potentially throwing an `InterruptedException`. ```java public interface BackoffPolicy { BackOffContext start(RetryContext context); void backOff(BackOffContext backOffContext) throws BackOffInterruptedException; } ``` -------------------------------- ### Register a MethodInvocationRetryListenerSupport for Reflective Invocations Source: https://github.com/spring-projects/spring-retry/blob/main/README.md This example demonstrates how to register a custom `MethodInvocationRetryListenerSupport` with a `RetryTemplate`. This listener allows detailed inspection of method invocations, such as extracting class and method names, and arguments, which is useful for monitoring and tagging retry attempts based on specific method calls. The `doOnSuccess` method enables custom result validation. ```java template.registerListener(new MethodInvocationRetryListenerSupport() { @Override protected void doClose(RetryContext context, MethodInvocationRetryCallback callback, Throwable throwable) { monitoringTags.put(labelTagName, callback.getLabel()); Method method = callback.getInvocation() .getMethod(); monitoringTags.put(classTagName, method.getDeclaringClass().getSimpleName()); monitoringTags.put(methodTagName, method.getName()); // register a monitoring counter with appropriate tags // ... @Override protected void doOnSuccess(RetryContext context, MethodInvocationRetryCallback callback, T result) { Object[] arguments = callback.getInvocation().getArguments(); // decide whether the result for the given arguments should be accepted // or retried according to the retry policy } } }); ``` -------------------------------- ### Build Spring Retry Project with Maven Source: https://github.com/spring-projects/spring-retry/blob/main/README.md This snippet provides the command to build the Spring Retry project using Maven. It requires Java 17 and Maven 3.0.5 or greater. ```bash $ mvn install ``` -------------------------------- ### Enabling Spring Retry and Registering Listeners Source: https://github.com/spring-projects/spring-retry/blob/main/README.md Demonstrates how to enable Spring Retry using `@EnableRetry` on a `@Configuration` class and apply `@Retryable` to a service method. It also shows how to register custom `RetryListener` beans for monitoring retry events. ```Java @Configuration @EnableRetry public class Application { @Bean public Service service() { return new Service(); } @Bean public RetryListener retryListener1() { return new RetryListener() {...} } @Bean public RetryListener retryListener2() { return new RetryListener() {...} } } @Service class Service { @Retryable(RemoteAccessException.class) public service() { // ... do something } } ``` -------------------------------- ### Configure RetryTemplate with Fluent API Source: https://github.com/spring-projects/spring-retry/blob/main/README.md Introduced in version 1.3, the fluent builder API provides a more readable and concise way to configure `RetryTemplate` instances. It allows chaining methods to set properties like max attempts, backoff policies, and retry conditions. ```java RetryTemplate.builder() .maxAttempts(10) .exponentialBackoff(100, 2, 10000) .retryOn(IOException.class) .traversingCauses() .build(); RetryTemplate.builder() .fixedBackoff(10) .withinMillis(3000) .build(); RetryTemplate.builder() .infiniteRetry() .retryOn(IOException.class) .uniformRandomBackoff(1000, 3000) .build(); ``` -------------------------------- ### Spring Retry Expression Evaluation Rules (APIDOC) Source: https://github.com/spring-projects/spring-retry/blob/main/README.md Details the evaluation context and timing for various expressions used in Spring Retry annotations. It covers how exceptionExpression is evaluated against the thrown exception, and how maxAttemptsExpression and @BackOff attributes are evaluated during initialization, with notes on runtime evaluation introduced in version 2.0 and argument availability. ```APIDOC Expression Evaluation Rules: - exceptionExpression: - Evaluated against the thrown exception as the #root object. - Templated expressions (#{...}) are deprecated in favor of simple expression strings (e.g., 'message.contains(\'this can be retried\')'). - maxAttemptsExpression & @BackOff expression attributes (delayExpression, maxDelayExpression, multiplierExpression): - Evaluated once, during initialization. - No root object for evaluation, but can reference other beans in the context. - Version 2.0+ Evaluation: - Expressions in @Retryable, @CircuitBreaker, and BackOff can be evaluated once (initialization) or at runtime. - Earlier versions: Always initialization (except Retryable.exceptionExpression). - Runtime evaluation: A root object containing method arguments is passed to the evaluation context. - Note: Arguments are null initially (not available until method called at least once). - Note: Arguments only available with stateless retry (includes @CircuitBreaker). ``` -------------------------------- ### Configure Spring Retry with Initial Expressions Source: https://github.com/spring-projects/spring-retry/blob/main/README.md Demonstrates how to use SpEL expressions for maxAttemptsExpression and BackOff attributes such as delayExpression, maxDelayExpression, and multiplierExpression within the @Retryable annotation. These expressions are typically evaluated during application initialization. ```Java maxAttemptsExpression = "@#integerFiveBean", backoff = @Backoff(delayExpression = "#{1}", maxDelayExpression = "#{5}", multiplierExpression = "#{1.1}")) public void service3() { ... } ``` -------------------------------- ### Add Spring Boot AOP Dependency for Declarative Retry Source: https://github.com/spring-projects/spring-retry/blob/main/README.md Specifies the Gradle dependency required for Spring Boot applications to enable the AOP functionality necessary for declarative retry handling using @Retryable annotations. ```Gradle runtimeOnly 'org.springframework.boot:spring-boot-starter-aop' ``` -------------------------------- ### Add Spring Retry Maven Dependency Source: https://github.com/spring-projects/spring-retry/blob/main/README.md This snippet shows the Maven XML configuration required to include the Spring Retry library as a dependency in your project. ```xml org.springframework.retry spring-retry ``` -------------------------------- ### Implementing Recovery Methods with @Recover Source: https://github.com/spring-projects/spring-retry/blob/main/README.md Shows how to define a recovery method using `@Recover` in the same class as the `@Retryable` method. The recovery method is invoked when retries are exhausted and can optionally accept the thrown exception and original method arguments for error handling. ```Java @Service class Service { @Retryable(retryFor = RemoteAccessException.class) public void service(String str1, String str2) { // ... do something } @Recover public void recover(RemoteAccessException e, String str1, String str2) { // ... error handling making use of original args if required } } ``` -------------------------------- ### Matching Generic Return Types for Recovery Methods Source: https://github.com/spring-projects/spring-retry/blob/main/README.md Illustrates how Spring Retry (version 1.3.2+) can match parameterized (generic) return types to correctly identify the appropriate `@Recover` method. This allows for distinct recovery logic based on the generic type of the returned object. ```Java @Service class Service { @Retryable(retryFor = RemoteAccessException.class) public List service1(String str1, String str2) { // ... do something } @Retryable(retryFor = RemoteAccessException.class) public List service2(String str1, String str2) { // ... do something } @Recover public List recover1(RemoteAccessException e, String str1, String str2) { // ... error handling for service1 } @Recover public List recover2(RemoteAccessException e, String str1, String str2) { // ... error handling for service2 } } ``` -------------------------------- ### Define the RetryListener Interface in Spring Retry Source: https://github.com/spring-projects/spring-retry/blob/main/README.md This snippet shows the `RetryListener` interface, which provides default methods for `open`, `onSuccess`, `onError`, and `close` callbacks. These methods allow developers to hook into different stages of the retry process, such as before/after the entire retry or for individual callback calls, enabling custom logic like monitoring or result validation. ```java public interface RetryListener { default boolean open(RetryContext context, RetryCallback callback) { return true; } default void onSuccess(RetryContext context, RetryCallback callback, T result) { } default void onError(RetryContext context, RetryCallback callback, Throwable throwable) { } default void close(RetryContext context, RetryCallback callback, Throwable throwable) { } } ``` -------------------------------- ### Define RetryOperations Interface Source: https://github.com/spring-projects/spring-retry/blob/main/README.md The `RetryOperations` interface defines the core strategy for retrying operations, providing overloaded `execute` methods to handle various use cases including recovery and state management. ```java public interface RetryOperations { T execute(RetryCallback retryCallback) throws E; T execute(RetryCallback recoveryCallback) throws E; T execute(RetryCallback retryCallback, RetryState retryState) throws E, ExhaustedRetryException; T execute(RetryCallback retryCallback, RecoveryCallback recoveryCallback, RetryState retryState) throws E; } ``` -------------------------------- ### Specifying Recovery Method by Name to Resolve Conflicts Source: https://github.com/spring-projects/spring-retry/blob/main/README.md Demonstrates how to explicitly specify the recovery method name using the `recover` attribute in `@Retryable` when multiple `@Recover` methods could apply. This ensures the correct recovery logic is invoked for specific retryable methods. ```Java @Service class Service { @Retryable(recover = "service1Recover", retryFor = RemoteAccessException.class) public void service1(String str1, String str2) { // ... do something } @Retryable(recover = "service2Recover", retryFor = RemoteAccessException.class) public void service2(String str1, String str2) { // ... do something } @Recover public void service1Recover(RemoteAccessException e, String str1, String str2) { // ... error handling making use of original args if required } @Recover public void service2Recover(RemoteAccessException e, String str1, String str2) { // ... error handling making use of original args if required } } ``` -------------------------------- ### Spring Retry Exception Classification Properties (APIDOC) Source: https://github.com/spring-projects/spring-retry/blob/main/README.md Describes the properties used for classifying exceptions within the @Retryable annotation, including retryFor, noRetryFor, and notRecoverable, and notes their relationship to deprecated properties. ```APIDOC @Retryable Exception Classification Properties: - retryFor: - Type: Class[] - Description: Specifies an array of exception types that should trigger a retry. - Replaces: 'include' (deprecated). - noRetryFor: - Type: Class[] - Description: Specifies an array of exception types that should NOT trigger a retry. - Replaces: 'exclude' (deprecated). - notRecoverable: - Type: Class[] - Description: Specifies an array of exception types for which recovery methods should be skipped. If an exception matches this, it is thrown to the caller either after retries are exhausted, or immediately if not retryable. ``` -------------------------------- ### Using SpEL Expressions in @Retryable Source: https://github.com/spring-projects/spring-retry/blob/main/README.md Demonstrates the use of Spring Expression Language (SpEL) within `@Retryable` attributes (introduced in version 1.2). This allows for dynamic retry conditions, such as retrying based on a specific message in the exception or using a custom bean for evaluation. ```Java @Retryable(exceptionExpression="message.contains('this can be retried')") public void service1() { ... } @Retryable(exceptionExpression="message.contains('this can be retried')") public void service2() { ... } @Retryable(exceptionExpression="@exceptionChecker.shouldRetry(#root)", ``` -------------------------------- ### Add AspectJ Weaver Dependency for Non-Boot AOP Source: https://github.com/spring-projects/spring-retry/blob/main/README.md Provides the Gradle dependency for non-Spring Boot applications to include AspectJ Weaver, which is essential for enabling AOP support for @Retryable annotations. ```Gradle runtimeOnly 'org.aspectj:aspectjweaver:1.9.20.1' ``` -------------------------------- ### Configure and Use SimpleRetryPolicy in Spring Retry Source: https://github.com/spring-projects/spring-retry/blob/main/README.md This Java code snippet demonstrates how to configure and apply a `SimpleRetryPolicy` within a `RetryTemplate`. It sets a maximum of 5 retry attempts for any `Exception` type. The `RetryTemplate` then executes a `RetryCallback` where the business logic resides, automatically applying the defined retry policy upon failure. ```java // Set the max attempts including the initial attempt before retrying // and retry on all exceptions (this is the default): SimpleRetryPolicy policy = new SimpleRetryPolicy(5, Collections.singletonMap(Exception.class, true)); // Use the policy... RetryTemplate template = new RetryTemplate(); template.setRetryPolicy(policy); template.execute(new RetryCallback() { public MyObject doWithRetry(RetryContext context) { // business logic here } }); ``` -------------------------------- ### Use Bean-Referenced Expressions in Spring Retry Source: https://github.com/spring-projects/spring-retry/blob/main/README.md Shows how to configure @Retryable and @BackOff attributes using SpEL expressions that reference properties from other Spring beans, such as @runtimeConfigs.maxAttempts, allowing for externalized and dynamic configuration. ```Java @Retryable(maxAttemptsExpression = "@runtimeConfigs.maxAttempts", backoff = @BackOff(delayExpression = "@runtimeConfigs.initial", maxDelayExpression = "@runtimeConfigs.max", multiplierExpression = "@runtimeConfigs.mult")) public void service() { ... } ``` -------------------------------- ### Define RetryCallback Interface Source: https://github.com/spring-projects/spring-retry/blob/main/README.md The `RetryCallback` interface allows developers to encapsulate business logic that needs to be retried. The `doWithRetry` method is executed, and if it throws an exception, the operation is retried. ```java public interface RetryCallback { T doWithRetry(RetryContext context) throws E; } ``` -------------------------------- ### Apply Custom Retry Annotations in Spring Service Source: https://github.com/spring-projects/spring-retry/blob/main/README.md This Java code demonstrates how to apply custom composed retry annotations, `@LocalRetryable` and `@RemoteRetryable`, to service methods. It shows how to specify included exceptions and recovery methods for different retry strategies, along with their corresponding recovery handlers. ```java @Service class Service { ... @LocalRetryable(include = TemporaryLocalException.class, recover = "service1Recovery") public List service1(String str1, String str2){ //... do something } public List service1Recovery(TemporaryLocalException ex,String str1, String str2){ //... Error handling for service1 } ... @RemoteRetryable(include = TemporaryRemoteException.class, recover = "service2Recovery") public List service2(String str1, String str2){ //... do something } public List service2Recovery(TemporaryRemoteException ex, String str1, String str2){ //... Error handling for service2 } ... } ``` -------------------------------- ### Define @LocalRetryable Custom Annotation Source: https://github.com/spring-projects/spring-retry/blob/main/README.md This Java code defines the `@LocalRetryable` custom annotation, which composes the base `@Retryable` annotation. It predefines retry parameters like `maxAttempts` and `backoff` for local service calls and uses `@AliasFor` to expose `recover`, `value`, `include`, `exclude`, and `label` attributes from the underlying `@Retryable` annotation. ```java @Target({ ElementType.METHOD, ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @Retryable(maxAttempts = "3", backoff = @Backoff(delay = "500", maxDelay = "2000", random = true) ) public @interface LocalRetryable { @AliasFor(annotation = Retryable.class, attribute = "recover") String recover() default ""; @AliasFor(annotation = Retryable.class, attribute = "value") Class[] value() default {}; @AliasFor(annotation = Retryable.class, attribute = "include") Class[] include() default {}; @AliasFor(annotation = Retryable.class, attribute = "exclude") Class[] exclude() default {}; @AliasFor(annotation = Retryable.class, attribute = "label") String label() default ""; } ``` -------------------------------- ### Implement RecoveryCallback for Exhausted Retries Source: https://github.com/spring-projects/spring-retry/blob/main/README.md When all retry attempts are exhausted without success, the `RecoveryCallback` provides an alternative path for processing. This allows clients to define fallback logic to handle situations where the primary operation cannot be recovered through retries. ```java MyObject myObject = template.execute(new RetryCallback() { public MyObject doWithRetry(RetryContext context) { // business logic here }, new RecoveryCallback() { MyObject recover(RetryContext context) throws Exception { // recover logic here } }); ``` -------------------------------- ### Define @RemoteRetryable Custom Annotation Source: https://github.com/spring-projects/spring-retry/blob/main/README.md This Java code defines the `@RemoteRetryable` custom annotation, composing the base `@Retryable` annotation. It sets specific retry parameters for remote service calls, such as `maxAttempts` and a more aggressive `backoff` strategy. It also uses `@AliasFor` to map attributes like `recover`, `value`, `include`, `exclude`, and `label` to the base `@Retryable` annotation. ```java @Target({ ElementType.METHOD, ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented @Retryable(maxAttempts = "5", backoff = @Backoff(delay = "1000", maxDelay = "30000", multiplier = "1.2", random = true) ) public @interface RemoteRetryable { @AliasFor(annotation = Retryable.class, attribute = "recover") String recover() default ""; @AliasFor(annotation = Retryable.class, attribute = "value") Class[] value() default {}; @AliasFor(annotation = Retryable.class, attribute = "include") Class[] include() default {}; @AliasFor(annotation = Retryable.class, attribute = "exclude") Class[] exclude() default {}; @AliasFor(annotation = Retryable.class, attribute = "label") String label() default ""; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.