Spring Cloud Feign Client Example
Welcome readers, in this tutorial, we will explore an interesting Spring Cloud component known as Netflix Feign Client to implement a declarative REST client.
1. Introduction
- Spring Boot is a module that provides rapid application development feature to the spring framework including auto-configuration, standalone-code, and production-ready code
- It creates applications that are packaged as jar and are directly started using embedded servlet container (such as Tomcat, Jetty or Undertow). Thus, no need to deploy the war files
- It simplifies the maven configuration by providing the starter template and helps to resolve the dependency conflicts. It automatically identifies the required dependencies and imports them in the application
- It helps in removing the boilerplate code, extra annotations, and xml configurations
- It provides a powerful batch processing and manages the rest endpoints
- It provides an efficient jpa-starter library to effectively connect the application with the relational databases
- It offers a Microservice architecture and cloud configuration that manages all the application related configuration properties in a centralized manner.
1.1 What is Netflix Feign Client?
Netflix Feign Client is a client binder for implementing the declarative REST client in a microservices architecture. Following diagram quickly summarizes the Feign Client.
Now, open the eclipse ide and let’s see how to implement this tutorial in spring boot. Make note, we will be using an existing client application created in Section 4.1 of the following link.
2. Spring Cloud Feign Client Example
Here is a systematic guide for implementing this tutorial.
2.1 Tools Used
We are using Eclipse Kepler SR2, JDK 8 and Maven.
2.2 Project Structure
In case you are confused about where you should create the corresponding files or folder, let us review the project structure of the spring boot application.
2.3 Project Creation
This section will demonstrate how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project
.
In the New Maven Project window, it will ask you to select a project location. By default, ‘Use default workspace location’ will be selected. Just click on the next button to proceed.
Select the Maven Web App archetype from the list of options and click next.
It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in Fig. 5. The version number will be by default: 0.0.1-SNAPSHOT
.
Click on Finish and the creation of the maven project will be completed. If you observe, it has downloaded the maven dependencies and a pom.xml
file will be created for the project. Let’s start building the application!
3. Application Creation
Below are the steps involved in developing the application.
3.1 Maven Dependencies
Here, we specify the dependencies for Spring Cloud, Netflix Hystrix, Netflix Ribbon, and Netflix Feign. Maven will automatically resolve the other dependencies. The updated file will have the following code.
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>jcg.tutorial</groupId> <artifactId>Springfeignclienttutorial</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>Spring Feign Client Tutorial</name> <url>http://maven.apache.org</url> <!-- spring boot parent dependency jar --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.3.RELEASE</version> </parent> <!-- importing the spring cloud parent pom as well --> <dependencyManagement> <dependencies> <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-parent --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-parent</artifactId> <version>Greenwich.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <!-- dependency to support web and restful applications using spring mvc --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- dependency to support eureka server --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka-server</artifactId> <version>1.4.6.RELEASE</version> </dependency> <!-- dependency to support feign client --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> <version>1.4.6.RELEASE</version> </dependency> <!-- dependency to support ribbon --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-ribbon</artifactId> <version>1.4.6.RELEASE</version> </dependency> <!-- dependency to support hystrix --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix</artifactId> <version>1.4.6.RELEASE</version> </dependency> </dependencies> <build> <finalName>Springfeignclienttutorial</finalName> </build> </project>
3.2 Configuration File
Create a new properties file at the Springfeignclienttutorial/src/main/resources/
location and add the following code to it.
application.properties
server.port=9191 spring.application.name=greetingsinfofeignclient eureka.client.serviceUrl.defaultZone=http://localhost:7171/eureka/
3.3 Implementation Class
Add the following code the main class to bootstrap the application from the main method. Always remember, the entry point of the spring boot application is the class containing @SpringBootApplication
annotation and the static main method.
Springfeignclient.java
package com.springcloud.feign; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.openfeign.EnableFeignClients; /** * @author yatinbatra * */ @SpringBootApplication // This annotation boostraps and auto-configure the application. @EnableDiscoveryClient // This annotation lists the application on the eureka server. @EnableFeignClients // This annotation enables feign client. @EnableCircuitBreaker // This annotation enables the circuit breaker for the microservice. public class Springfeignclient { public static void main(String[] args) { SpringApplication.run(Springfeignclient.class, args); } }
3.4 Feign Client Interface
Add the following code to the feign interface. This interface will be responsible for calling the greetings
application for getting the response.
Greetingsclient.java
package com.springcloud.feign.controller; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @FeignClient(name= "greetings") public interface Greetingsclient { /** * Interface method to get the greetings information from a different microservice. * @param langCode * @return */ @GetMapping(value= "/greet/welcome/{localeId}") public String getGreetings(@PathVariable(name= "localeId") String langCode); }
3.5 Controller Class
Add the following code to the controller class. Please note, this controller class for testing purpose only and the developers can access it via the following link – localhost:9191/feign/getGreetings/en
.
Restcontroller.java
package com.springcloud.feign.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; // Application url - localhost:9191/feign/getGreetings/en @RestController @RequestMapping(value= "/feign") public class Feignclientcontroller { @Autowired Greetingsclient greetingsfeignclient; /** * Method to fetch the greetings information from the different microservices via feign client (i.e. declarative approach). * @param langCode * @return */ @GetMapping(value="/getGreetings/{localeId}", produces= MediaType.APPLICATION_JSON_VALUE) @HystrixCommand(fallbackMethod= "defaultResponse") public ResponseEntity<String> getGreetingsAndUserInfoViaFeign(@PathVariable(name= "localeId") String langCode) { System.out.println("Using the feign client controller to fetch the greetings information for locale= " + langCode); // Fetching the greetings salutation for the given locale. // Data is fetched from thr greetings microservice hosted on port no. - 8181 String greetMsg = greetingsfeignclient.getGreetings(langCode); System.out.println("Welcome msg for locale= " + langCode + ", is= " + greetMsg); // Sending the response return new ResponseEntity<String>(greetMsg, HttpStatus.OK); } // When we define a fallback method, the fallback-method must match the same parameters of the method where you define the Hystrix Command using the hystrix-command annotation. public ResponseEntity<String> defaultResponse(String err) { System.out.println("You are seeing this fallback response because the underlying microservice is down."); err = "Fallback error as the microservice is down."; return new ResponseEntity<String>(err, HttpStatus.INTERNAL_SERVER_ERROR); } }
4. Run the Applications
As we are ready with all the changes, let us compile the projects and run the applications as a java project.
- Right click on the
WelcomeApp.java
class,Run As -> Java Application
. The client microservice will be started on the8181
port - Right click on the
Springfeignclient.java
class,Run As -> Java Application
. The client microservice will be started on the9191
port
Developers can debug the example and see what happens after every step. Enjoy!
5. Project Demo
Now hit the following application url on your favorite browser and developers will see the output page.
localhost:9191/feign/getGreetings/en
Developers can refer to application logs for the detailed flow of the output. That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!
6. Conclusion
In this section, developers learned how to create a feign client application. Developers can download the sample application as an Eclipse project in the Downloads section.
7. Download the Eclipse Project
This was an example of implementing the Netflix Feign Client with Spring Cloud.
You can download the full source code of this example here: Spring Cloud Feign Client Example
Why feign clients are necessary? As from the codes, it can be seen that,
– they use the same amount of code than a RestController . @GetMapping value, @PathVaiable etc
– Say, we have a rest controller XYZ with URL mapping details. With Feign, we define another controller, another service to invoke XYZ. So define a controller over controller. Is that correct?