Spring Retry and Guava Retry Frameworks: Concepts, Configuration, and Practical Code Examples
This article provides a comprehensive guide to using Spring Retry and Guava Retry in Java applications, covering dependency setup, basic and annotation-based usage, various retry and back‑off policies, code examples, and a comparison of both frameworks to help developers implement robust retry mechanisms.
The article introduces Spring Retry , a Spring component that offers declarative retry support for Spring applications, including batch processing, integration, and Hadoop. It explains how to add the required Maven dependency and presents a simple task method that randomly throws exceptions or returns boolean values.
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
<version>1.2.2.RELEASE</version>
</dependency>A sample RetryDemoTask class is shown, demonstrating how different random values trigger different outcomes (success, false, or exceptions) and how logging is performed.
The article then demonstrates using RetryTemplate to configure retry behavior programmatically. It creates a RetryTemplate instance, sets a FixedBackOffPolicy with a 1‑second interval, and defines a SimpleRetryPolicy with a maximum of three attempts and a map of retryable exceptions (e.g., RemoteAccessException). The execute method receives a RetryCallback for the main logic and a RecoveryCallback for handling exhausted retries.
RetryTemplate retryTemplate = new RetryTemplate();
FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
backOffPolicy.setBackOffPeriod(fixedPeriodTime);
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(maxRetryTimes, exceptionMap);
retryTemplate.setRetryPolicy(retryPolicy);
retryTemplate.setBackOffPolicy(backOffPolicy);
Boolean execute = retryTemplate.execute(
retryContext -> {
boolean b = RetryDemoTask.retryTask("abc");
log.info("调用的结果:{}", b);
return b;
},
retryContext -> {
log.info("已达到最大重试次数或抛出了不重试的异常~~~");
return false;
}
);
log.info("执行结果:{}", execute);The article also lists various built‑in retry policies such as NeverRetryPolicy, AlwaysRetryPolicy, SimpleRetryPolicy, TimeoutRetryPolicy, ExceptionClassifierRetryPolicy, CircuitBreakerRetryPolicy, and CompositeRetryPolicy, describing their characteristics.
Back‑off strategies are covered next, including NoBackOffPolicy, FixedBackOffPolicy, UniformRandomBackOffPolicy, ExponentialBackOffPolicy, and ExponentialRandomBackOffPolicy, with details on configuration parameters such as delay, multiplier, and random intervals.
For annotation‑based usage, the article shows how to enable retry with @EnableRetry on the Spring Boot application class and apply @Retryable on methods, specifying retryable exceptions, maximum attempts, and back‑off settings. A corresponding @Recover method is provided to handle failure after all retries.
@EnableRetry
public class Application { ... }
@Service
@Slf4j
public class SpringRetryDemo {
@Retryable(value = {RemoteAccessException.class}, maxAttempts = 3,
backoff = @Backoff(delay = 2000L, multiplier = 2))
public boolean call(String param) {
return RetryDemoTask.retryTask(param);
}
@Recover
public boolean recover(Exception e, String param) {
log.error("达到最大重试次数,或抛出了一个没有指定进行重试的异常:", e);
return false;
}
}After covering Spring Retry, the article switches to Guava Retry , a thread‑safe retry library that works with java.util.concurrent.Callable. It adds the Maven dependency for guava-retrying and presents a task method similar to the Spring example but with additional result‑based retry logic. com.github.rholder:guava-retrying:2.0.0 Using RetryerBuilder, the article configures retry conditions based on exception type ( RemoteAccessException) and result ( false), a fixed wait strategy of 3 seconds, and a stop strategy after three attempts. The retryer is then executed with a lambda that calls RetryDemoTask.retryTask("abc").
Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
.retryIfExceptionOfType(RemoteAccessException.class)
.retryIfResult(res -> res == false)
.withWaitStrategy(WaitStrategies.fixedWait(3, TimeUnit.SECONDS))
.withStopStrategy(StopStrategies.stopAfterAttempt(3))
.build();
try {
retryer.call(() -> RetryDemoTask.retryTask("abc"));
} catch (Exception e) {
e.printStackTrace();
}The article explains additional Guava retry options such as retryIfException, retryIfRuntimeException, retryIfExceptionOfType, result‑based predicates, and RetryListener for logging each retry attempt.
Finally, a summary compares the two frameworks, noting that both are thread‑safe and suitable for concurrent scenarios, but Guava Retry offers more flexible result‑based retry conditions, while Spring Retry relies on exception handling.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
