In this post under Spring Retry, I will introduce with example another out of the box implementation of BackOffPolicy i.e., ExponentialBackOffPolicy.
ExponentialBackOffPolicy increases the backoff period at every retry attempt by a specified number.
ExponentialBackOffPolicy requires three inputs for it to work, which are
1) initialInterval –> the backoff period used at first retry
2) maxInterval –> the max backoff period that is allowed at retry attempt. Spring Retry doesn’t wait more than maxInterval between retry attempts.
3) multiplier –> the value by which backoff period has to incremented at every retry attempt.
Below is the xml configuration
XML code
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
5 <bean id="backOffPolicy" class="org.springframework.retry.backoff.ExponentialBackOffPolicy">
6 <property name="initialInterval" value="100"/>
7 <property name="maxInterval" value="300000"/>
8 <property name="multiplier" value="1200"/>
9 </bean>
10
11 <bean id="retryTemplate" class="org.springframework.retry.support.RetryTemplate">
12 <property name="backOffPolicy" ref="backOffPolicy"/>
13 </bean>
14
15 <bean id="service5" class="Service5"/>
16 </beans>
As per the above xml configuration from line 6 to 9, the Spring Retry will wait for 100 ms when retrying first time. Then for every subsequent retry, the back off period is increased by multiplier 1200ms. The backoff period will be incremented at every backoff by 1200 untill it goes beyond the 300000 ms.
In this way we can use ExponentialBackOffPolicy.
Below is the Service and Main class code for your reference.
Service class
import java.util.Date;
public class Service5 {
private int i = 0;
public void executeWithException() {
i = i + 1;
System.out.println("Executing method 'executeWithException' : " + i + " at " + new Date());
throw new NullPointerException();
}
}
Main class
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.retry.support.RetryTemplate;
public class Example14 {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Example14.xml");
Service5 service5 = (Service5)context.getBean("service5");
RetryTemplate retryTemplate = (RetryTemplate)context.getBean("retryTemplate");
retryTemplate.execute(retryContext -> { service5.executeWithException(); return null; });
}
}
Note
Press like button if you like the post. Also share your opinion regarding posts through comments. Also mention what other framework you want me to cover through comments.