Skip to content

Allow composing @Retryable annotation with @AliasFor recover method #313

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 88 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -654,6 +654,94 @@ line to your `build.gradle` file:
```
runtime('org.aspectj:aspectjweaver:1.8.13')
```
### Further customizations

Starting from version 1.3.2 and later `@Retryable` annotation can be used in custom composed annotations to create your own annotations with predefined behaviour.
For example if you discover you need two kinds of retry strategy, one for local services calls, and one for remote services calls, you could decide
to create two custom annotations `@LocalRetryable` and `@RemoteRetryable` that differs in the retry strategy as well in the maximum number of retries.

To make custom annotation composition work properly you can use `@AliasFor` annotation, for example on the `recover` method, so that you can further extend the versatility of your custom annotations and allow the `recover` argument value
to be picked up as if it was set on the `recover` method of the base `@Retryable` annotation.

Usage Example:
```java
@Service
class Service {
...

@LocalRetryable(include = TemporaryLocalException.class, recover = "service1Recovery")
public List<Thing> service1(String str1, String str2){
//... do something
}

public List<Thing> service1Recovery(TemporaryLocalException ex,String str1, String str2){
//... Error handling for service1
}
...

@RemoteRetryable(include = TemporaryRemoteException.class, recover = "service2Recovery")
public List<Thing> service2(String str1, String str2){
//... do something
}

public List<Thing> service2Recovery(TemporaryRemoteException ex, String str1, String str2){
//... Error handling for service2
}
...
}
```

```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<? extends Throwable>[] value() default {};

@AliasFor(annotation = Retryable.class, attribute = "include")

Class<? extends Throwable>[] include() default {};

@AliasFor(annotation = Retryable.class, attribute = "exclude")
Class<? extends Throwable>[] exclude() default {};

@AliasFor(annotation = Retryable.class, attribute = "label")
String label() default "";

}
```

```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<? extends Throwable>[] value() default {};

@AliasFor(annotation = Retryable.class, attribute = "include")
Class<? extends Throwable>[] include() default {};

@AliasFor(annotation = Retryable.class, attribute = "exclude")
Class<? extends Throwable>[] exclude() default {};

@AliasFor(annotation = Retryable.class, attribute = "label")
String label() default "";

}
```

### XML Configuration

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,13 @@
import java.util.Map;

import org.springframework.classify.SubclassClassifier;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.retry.ExhaustedRetryException;
import org.springframework.retry.RetryContext;
import org.springframework.retry.interceptor.MethodInvocationRecoverer;
import org.springframework.retry.support.RetrySynchronizationManager;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.ReflectionUtils.MethodCallback;
import org.springframework.util.StringUtils;

/**
Expand All @@ -53,6 +52,7 @@
* @author Maksim Kita
* @author Gary Russell
* @author Artem Bilan
* @author Gianluca Medici
*/
public class RecoverAnnotationRecoveryHandler<T> implements MethodInvocationRecoverer<T> {

Expand Down Expand Up @@ -196,12 +196,12 @@ private boolean compareParameters(Object[] args, int argCount, Class<?>[] parame
private void init(final Object target, Method method) {
final Map<Class<? extends Throwable>, Method> types = new HashMap<>();
final Method failingMethod = method;
Retryable retryable = AnnotationUtils.findAnnotation(method, Retryable.class);
Retryable retryable = AnnotatedElementUtils.findMergedAnnotation(method, Retryable.class);
if (retryable != null) {
this.recoverMethodName = retryable.recover();
}
ReflectionUtils.doWithMethods(target.getClass(), candidate -> {
Recover recover = AnnotationUtils.findAnnotation(candidate, Recover.class);
Recover recover = AnnotatedElementUtils.findMergedAnnotation(candidate, Recover.class);
if (recover == null) {
recover = findAnnotationOnTarget(target, candidate);
}
Expand Down Expand Up @@ -270,7 +270,7 @@ private void putToMethodsMap(Method method, Map<Class<? extends Throwable>, Meth
private Recover findAnnotationOnTarget(Object target, Method method) {
try {
Method targetMethod = target.getClass().getMethod(method.getName(), method.getParameterTypes());
return AnnotationUtils.findAnnotation(targetMethod, Recover.class);
return AnnotatedElementUtils.findMergedAnnotation(targetMethod, Recover.class);
}
catch (Exception e) {
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@

package org.springframework.retry.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
Expand All @@ -24,6 +29,7 @@

import org.junit.jupiter.api.Test;

import org.springframework.core.annotation.AliasFor;
import org.springframework.retry.ExhaustedRetryException;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ReflectionUtils;
Expand All @@ -37,6 +43,7 @@
* @author Randell Callahan
* @author Nathanaël Roberts
* @author Maksim Kita
* @Author Gianluca Medici
*/
public class RecoverAnnotationRecoveryHandlerTests {

Expand Down Expand Up @@ -278,6 +285,14 @@ public void recoverByRetryableNameWithPrimitiveArgs() {
assertThat(handler.recover(new Object[] { 2 }, new RuntimeException("Planned"))).isEqualTo(2);
}

@Test
public void recoverByComposedRetryableAnnotationName() {
Method foo = ReflectionUtils.findMethod(RecoverByComposedRetryableAnnotationName.class, "foo", String.class);
RecoverAnnotationRecoveryHandler<?> handler = new RecoverAnnotationRecoveryHandler<Integer>(
new RecoverByComposedRetryableAnnotationName(), foo);
assertThat(handler.recover(new Object[] { "Kevin" }, new RuntimeException("Planned"))).isEqualTo(4);
}

private static class InAccessibleRecover {

@Retryable
Expand Down Expand Up @@ -634,6 +649,23 @@ public int barRecover(Throwable throwable, String name) {

}

protected static class RecoverByComposedRetryableAnnotationName
implements RecoverByComposedRetryableAnnotationNameInterface {

public int foo(String name) {
return 0;
}

public int fooRecover(Throwable throwable, String name) {
return 1;
}

public int barRecover(Throwable throwable, String name) {
return 2;
}

}

protected interface RecoverByRetryableNameInterface {

@Retryable(recover = "barRecover")
Expand Down Expand Up @@ -677,4 +709,28 @@ protected interface RecoverByRetryableNameWithPrimitiveArgsInterface {

}

protected interface RecoverByComposedRetryableAnnotationNameInterface {

@ComposedRetryable(recover = "barRecover")
public int foo(String name);

@Recover
public int fooRecover(Throwable throwable, String name);

@Recover
public int barRecover(Throwable throwable, String name);

}

@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Retryable(maxAttempts = 4)
public @interface ComposedRetryable {

@AliasFor(annotation = Retryable.class, attribute = "recover")
String recover() default "";

}

}