Explore the power of microservices with Spring Cloud OpenFeign and Netflix Eureka. Learn how to build scalable and resilient applications using the latest technologies.
Declarative REST Clients: Feign and Its Role
Feign, a declarative web service client developed by Netflix, simplifies writing web service clients by leveraging a straightforward, annotation-driven approach. Developers can effortlessly create clients that interact with remote services by defining an interface and annotating it with relevant configurations. Feign’s extensibility is further bolstered by its support for pluggable annotations, encoders, and decoders, allowing for seamless integration with various frameworks and technologies.
Spring Cloud, a pivotal component of the Spring ecosystem, enhances Feign’s capabilities by introducing support for Spring MVC annotations and the same HttpMessageConverters
employed in Spring Web. This integration streamlines the development process and ensures consistency across the application stack, fostering a cohesive and maintainable codebase.
Integrating Eureka for Service Discovery
One of the fundamental aspects of a microservices-based architecture is service discovery, which enables applications to locate and communicate with one another dynamically. Eureka, a service discovery server and client developed by Netflix, plays a crucial role in this domain. Spring Cloud seamlessly integrates Eureka, allowing instances to register themselves and clients to discover these instances through Spring-managed beans.
By leveraging Spring Cloud’s autoconfiguration and binding capabilities, developers can quickly enable and configure Eureka within their Spring Boot applications. With a few simple annotations, such as @EnableDiscoveryClient
and @EnableEurekaServerApplications
can effortlessly participate in the service discovery process, facilitating the creation of highly scalable and resilient distributed systems.
Embracing Spring Cloud OpenFeign
Spring Cloud OpenFeign is a pivotal component that brings the power of Feign to the Spring ecosystem. By integrating Feign with Spring Cloud LoadBalancer, Spring Cloud OpenFeign enables the creation of load-balanced HTTP clients, ensuring efficient distribution of requests across multiple service instances.
To include Feign in a Spring Boot project, developers can leverage the spring-cloud-starter-openfeign
starter, simplifying the setup process and automatically configuring the necessary dependencies. This starter also supports Spring Cloud LoadBalancer, enabling seamless integration with various load-balancing strategies.
Overriding Feign Defaults and Customization
While Spring Cloud OpenFeign offers a comprehensive set of default configurations, it also provides ample opportunities for customization. Developers can override the default behavior by declaring additional configuration classes using the @FeignClient
annotation. This approach allows for fine-grained control over various aspects of the Feign client, such as the decoder, encoder, contract, and request interceptors.
Furthermore, Spring Cloud OpenFeign supports configuration properties, enabling developers to specify client-specific configurations through a centralized configuration file. This approach promotes code reusability and maintainability, as developers can easily adjust client configurations without modifying the codebase.
Ready to get started? Dive in and experience the magic of Spring Cloud OpenFeign and Spring Cloud Netflix Eureka for yourself.
Set up the Eureka server and client.

Set up the Spring Cloud OpenFeign.
1. The developer can create a Spring Cloud OpenFeign project from Spring initialzr.
2. Initial project with spring initialize
3. Add Dependencies.
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-loadbalancer</artifactId> </dependency>
Create the Feign Client.
1. The developer creates an interface for your Feign client that will communicate with the service registered in Eureka.
import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; @FeignClient(name = "eureka-client") public interface ServiceFeignClient { @GetMapping("/hostname") String getHostNameResponse(); }
2. Create the Feign Client Application.
import com.example.openfeign.feign_client.ServiceFeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HostNameController { private final ServiceFeignClient serviceFeignClient; public HostNameController(ServiceFeignClient serviceFeignClient) { this.serviceFeignClient = serviceFeignClient; } @GetMapping("/openfeign-hostname") public String getServiceData() { return serviceFeignClient.getHostNameResponse(); } }
Configuration Properties and Customization
Spring Cloud OpenFeign provides a comprehensive set of configuration properties that allow developers to fine-tune various aspects of their Feign clients. These properties include connection timeouts, read timeouts, logger levels, error decoders, retries, request interceptors, and more.
Developers can specify these configurations through centralized configuration files, promoting code reusability and maintainability. Additionally, Spring Cloud OpenFeign offers the flexibility to override configurations per client, enabling granular control over individual client behaviors.
1. For simple configuration. In the application.yml
For the Feign client.
spring: application: name: openfeign server: port: 8082 eureka: client: service-url: defaultZone: http://localhost:8761/eureka
2. Developers create a Dockerfile.
# Stage 1: Build the JAR file FROM maven:3.9.7-amazoncorretto-21 AS build WORKDIR /app COPY pom.xml . COPY src ./src RUN mvn clean package -DskipTests # Stage 2: Run the application FROM amazoncorretto:21-alpine VOLUME /tmp COPY --from=build /app/target/*.jar open-feign.jar ENTRYPOINT ["java", "-jar", "/open-feign.jar"]
3. Developers create a Docker compose.
version: '3.8' services: open-feign: build: context: . dockerfile: Dockerfile container_name: open-feign environment: - EUREKA_CLIENT_SERVICEURL_DEFAULTZONE=http://eureka-server:8761/eureka/ ports: - "8082:8082" networks: - eureka_eureka-network networks: eureka_eureka-network: external: true
Start the Spring Cloud OpenFeign server.
Developers start the server with the Docker command.
>docker compose up -d
The -d
flag in the docker-compose up -d
Command stands for “detached mode.” When you run Docker Compose with the -d
flag, the containers start in the background, allowing you to continue using the terminal.
Check the image of the Spring Cloud OpenFeign.
>docker images REPOSITORY TAG IMAGE ID CREATED SIZE openfeign-open-feign latest 2f713b8c7059 About an hour ago 367MB
Check the Spring Cloud OpenFeign container.
>docker container ls CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 23b049e1eaca openfeign-open-feign "java -jar /open-fei…" About an hour ago Up About an hour 0.0.0.0:8082->8082/tcp open-feign
Start the Spring Cloud OpenFeign server.
The developer sends a request to the server by using the command.
>curl http://localhost:8082/openfeign-hostname StatusCode : 200 StatusDescription : Content : f8242499fffa RawContent : HTTP/1.1 200 Keep-Alive: timeout=60 Connection: keep-alive Content-Length: 12 Content-Type: text/plain;charset=UTF-8 Date: Mon, 09 Sep 2024 10:43:19 GMT f8242499fffa Forms : {} Headers : {[Keep-Alive, timeout=60], [Connection, keep-alive], [Content-Length, 12], [Content-Type, text/plain;charset=UTF-8]...} Images : {} InputFields : {} Links : {} ParsedHtml : mshtml.HTMLDocumentClass RawContentLength : 12
Conclusion
Spring Cloud OpenFeign service discovers Eureka clients in the Eureka server. Eureka clients send responses correctly through the OpenFeign service.
Feign Hystrix Support and Fallbacks
In Spring Cloud, Feign simplifies HTTP calls, and Hystrix provides resilience features such as circuit breakers to handle failures. Although Hystrix has been deprecated in favor of Resilience4j, some projects may still use it for backward compatibility.
Setting Up Feign with Hystrix
Developers integrate Feign with Hystrix in a Spring Boot application.
1. Add a Maven dependency.
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-hystrix --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> <version>2.2.10.RELEASE</version> </dependency>
2. Since Spring Boot version 2.5.12, the @EnableCircuitBreaker
Annotation has been marked as deprecated. This means that developers no longer need to use it in their applications. Similarly, the @EnableEurekaClient
An annotation is also unnecessary. Instead, developers should include these two dependencies in their projects to ensure proper functionality.
spring-cloud-starter-circuitbreaker-resilience4j org.springframework.cloud:spring-cloud-starter-netflix-eureka-client
3. In addition, make sure your application.yml
or application.properties
The file has the following settings to enable Hystrix for Feign:
feign: hystrix: enabled: true
4. Create a Feign Client Interface: Define your Feign client interface and add a fallback class to handle failure scenarios:
import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; @FeignClient(name = "EUREKA-CLIENT", fallback = ServiceFeignClientFallback.class) public interface ServiceFeignClient { @GetMapping("/hostname") String getHostNameResponse(); }
5. Define a Fallback Class: Implement a fallback class that will provide default behavior when the Feign client call fails. This fallback class should implement the same interface as the Feign client:
import org.springframework.stereotype.Component; @Component public class ServiceFeignClientFallback implements ServiceFeignClient{ @Override public String getHostNameResponse() { return "Default response due to service failure"; } }
6. Enable Circuit Breaker: In your Spring Boot application class, you can enable Hystrix and Feign by using the @EnableFeignClients
and @EnableCircuitBreaker
Annotations:
@SpringBootApplication @EnableEurekaClient @EnableFeignClients @EnableCircuitBreaker public class OpenfeignApplication { public static void main(String[] args) { SpringApplication.run(OpenfeignApplication.class, args); } }
Fallback Factory for More Control
If developers want more control over the fallback behavior, they can use the FallbackFactory. This allows you to pass the exception to the fallback class and handle it accordingly:
import org.springframework.cloud.openfeign.FallbackFactory; import org.springframework.stereotype.Component; @Component public class ServiceGeignClientFallbackFactory implements FallbackFactory<ServiceFeignClient> { @Override public ServiceFeignClient create(Throwable cause) { return new ServiceFeignClient() { @Override public String getHostNameResponse() { return "Fallback triggered due to: " + cause.getMessage(); } }; } }
Conclusion
Feign Hystrix Support and Fallbacks for the project use the spring boot version below 2.5.12; if the project’s spring boot version is above 3, it is recommended to use Resilience4j instead.
Finally
Spring Cloud OpenFeign and Netflix Eureka are potent tools that empower developers to build scalable, resilient, high-performing applications in the ever-evolving microservices and distributed systems world. By leveraging declarative REST clients, service discovery, and a suite of advanced features, developers can effectively tackle the challenges of modern software development, fostering innovation and enabling the creation of robust, modular systems.