In this post, under Spring Retry I will show with example how to configure UniformRandomBackOffPolicy using annotations
For our example we will use the below service class
Service class
1 package defaultPackage;
2
3 import java.util.Date;
4
5 import org.springframework.retry.annotation.Backoff;
6 import org.springframework.retry.annotation.Retryable;
7 import org.springframework.stereotype.Service;
8
9 @Service
10 public class Service14 {
11 private int i = 0;
12
13 @Retryable(backoff = @Backoff(delay = 60000, maxDelay = 600000))
14 public void executeWithException() {
15 i = i + 1;
16 System.out.println("Executing method 'executeWithException' : " + i + " at " + new Date());
17 throw new NullPointerException();
18 }
19 }
As you can see in the above code, the method which has to be retried is annotated with “Retryable” annotation.
The “Retryable” annotation itself has “backoff” attribute which can be used to configure UniformRandomBackOffPolicy.
We use another annotation “Backoff” to set the “backoff” attribute.
We need to set two attributes of “Backoff” annotation, which is “delay” and “maxDelay” as shown at line 13.
The value of “delay” and “maxDelay” will be in ms.
In this way we can configure UniformRandomBackOffPolicy using annotations.
Below is the main method which calls the above service class.
Main Class
package defaultPackage;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.annotation.EnableRetry;
@Configuration
@EnableRetry
public class Example35 {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(Example35.class);
Service14 service14 = (Service14) context.getBean("service14");
try {
service14.executeWithException();
} catch(Exception excep) {
excep.printStackTrace();
}
}
@Bean(name="service14")
public Service14 getService() {
return new Service14();
}
}