Table of Contents
Introduction
Utilizing REST endpoints to communicate with external services is a routine task, streamlined by frameworks such as Feign. Nevertheless, encountering errors during these interactions is not uncommon, as various issues, often transient or unpredictable, may arise.
In this guide, we will explore strategies to handle failed requests effectively, enhancing the resilience of our REST clients through retry mechanisms. To retry Feign calls in Spring Boot, you can utilize the Retryer
interface provided by Feign along with Spring’s configuration capabilities.
Add Feign Dependency
Make sure you have Feign dependency included in your pom.xml
or build.gradle
For Maven:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
For Gradle:
implementation 'org.springframework.cloud:spring-cloud-starter-openfeign'
Create Feign Client Interface
Define your Feign client interface as you would normally do.
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
@FeignClient(name = "learn-spring-boot-online-service", url = "https://learnspringbootonline.com")
public interface LearnSpringBootOnlineFeignClient {
@GetMapping("/endpoint")
String fetchData();
}
Configure Retry
Configure the retry mechanism for Feign. You can create a configuration class to define the retry behavior.
import feign.Retryer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FeignClientConfig {
@Bean
public Retryer feignRetryer() {
return new Retryer.Default(100, 1000, 3); // Retry 3 times with 100ms initial interval and 1000ms max interval
}
}
Usage
Now you can use your Feign client in your services or controllers as needed.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class LearnSpringBootOnlineController {
@Autowired
private LearnSpringBootOnlineFeignClient feignClient;
@GetMapping("/fetchData")
public String fetchData() {
return feignClient.fetchData();
}
}
Testing
Test your application to ensure that Feign calls are retried as per the configured behavior.
Conclusion
In conclusion, implementing retry functionality for Feign calls in Spring Boot enhances the robustness and reliability of our REST client interactions with external services. By configuring a custom Retryer bean, we can effectively handle transient errors and ensure smoother communication with remote endpoints. This approach not only simplifies error recovery but also contributes to building more resilient and fault-tolerant microservice architectures.
Follow this blog post to implement custom error decoder for your feign client.
Explore our diverse collection of blogs covering a wide range of topics here.