Microservices Communication: Feign as Rest Client


In the previous microservice tutorial, we have learned How Microservice communicates with each other using RestTemplate. In this tutorial, we will learn How one microservice communicates with Other via Feign Client . This is the third part of Microservice Communication series.



What is a Feign Client?

Netflix provides Feign as an abstraction over Rest-based calls, by which Microservice can communicate with each other, But developers don’t have to bother about Rest internal details.

Why we use Feign Client?

In my previous tutorial, When EmployeeDashBoard service communicate with EmployeeService, Programmatically we had constructed the URL of dependent Microservice-- then call the service Using RestTemplate so we need to aware about the RestTemplate API to communicate with other microservice, which is certainly not part of our Business logic-- So question is Why should developer has  to know details of  Rest- API, Microservice developers only concentrate on Business logic so Spring Address this issues and comes with Feign Client which works on  declarative principle . We have to create an Interface/contract then Spring creates the original implementation on the fly so Rest-based service call is abstracted from developers. Not only that if you want to customize the call like Encode your request or decode the response in a Custom Object, Logging -- you can do it by Feign in a declarative way.  Feign a client is an important tool for Microservice developer to communicate with other Microservices via Rest API.


spring boot microservices--FeignClient






Coding Time:


Here we will alter our EmployeeDashborad Service to make it Feign enable;
Step 1 : we will add feign dependency into EmployeeDashBoard Service.

<dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-starter-feign</artifactId>
    </dependency>

Step 2: Now, We have to create an Interface where we declare the services which we wanted to call, Please note that the Service Request mapping is same as  EmployeeSerach Service Rest URL. Feign will call this URL when we call EmployeeDashBorad service.

Feign dynamically generate the Implementation of the interface which  we created , So Feign has to know which service to call before hand that's why we need to give a name of the interface which is the {Service-Id} of Employee Service, Now Feign contact to Eureka server with this Service Id and resolve the actual Ip/Host name of the Employee Service and call the URL provided in Request Mapping.
NB : when using @PathVariable for Feign Client use value property always unless it will give you the error java.lang.IllegalStateException: PathVariable annotation was empty on param 0


package com.example.EmployeeDashBoardService.controller;

import java.util.Collection;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.example.EmployeeDashBoardService.domain.model.EmployeeInfo;



@FeignClient(name="EmployeeSearch" )//Service Id of EmployeeSerach service
public interface EmployeeServiceProxy {
   
   @RequestMapping("/employee/find/{id}")
   public EmployeeInfo findById(@PathVariable(value="id") Long id);
   
   @RequestMapping("/employee/findall")
   public Collection<EmployeeInfo> findAll();

}

Step 3 : Now we will create a FeignEmployeeInfoController where we autowired our Interface so in runtime Spring can Inject actual implementation, then we call that implementation to call EmployeeService Rest API.

package com.example.EmployeeDashBoardService.controller;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.EmployeeDashBoardService.domain.model.EmployeeInfo;

@RefreshScope
@RestController
public class FeignEmployeeInfoController {
   
   @Autowired
   EmployeeServiceProxy proxyService;
   
   @RequestMapping("/dashboard/feign/{myself}")
   public EmployeeInfo findme(@PathVariable Long myself){
      return proxyService.findById(myself);
     
   }
   
   @RequestMapping("/dashboard/feign/peers")
   public  Collection<EmployeeInfo> findPeers(){
        return proxyService.findAll();
   }

}


Step 4: At Last , we need to tell our project that we will use Feign client so please scan it’s annotation. For this , we need to add @EnableFeignClients annotation on top of
EmployeeDashBoardServiceApplication

package com.example.EmployeeDashBoardService;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@EnableDiscoveryClient
@EnableFeignClients
@SpringBootApplication
public class EmployeeDashBoardServiceApplication {

   public static void main(String[] args) {
      SpringApplication.run(EmployeeDashBoardServiceApplication.class, args);
   }
   
   @Bean
   public RestTemplate restTemplate(RestTemplateBuilder builder) {
      return builder.build();
   }
}


Now we are all set for use Feign client.

Testing Time:

Start the following Microservices in order.

  1. EmployeeConfigServer
  2. EmployeeEurekaServer
  3. EmpolyeeSerachService.
  4. EmployeeDashBoardService


Now hit the url  http://localhost:8081/dashboard/feign/peers in browser

You will see following output

[
   {
      "employeeId": 1,
      "name": "Shamik  Mitra",
      "practiceArea": "Java",
      "designation": "Architect",
      "companyInfo": "Cognizant"
   },
   {
      "employeeId": 2,
      "name": "Samir  Mitra",
      "practiceArea": "C++",
      "designation": "Manager",
      "companyInfo": "Cognizant"
   },
   {
      "employeeId": 3,
      "name": "Swastika  Mitra",
      "practiceArea": "AI",
      "designation": "Sr.Architect",
      "companyInfo": "Cognizant"
   }
]