Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Microservices Communication: Feign as REST Client

DZone's Guide to

Microservices Communication: Feign as REST Client

Learn how to enable Feign client, a tool that allows microservices to communicate with other microservices via REST API.

· Microservices Zone ·
Free Resource

Learn how modern cloud architectures use of microservices has many advantages and enables developers to deliver business software in a CI/CD way.

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

What Is a Feign Client?

Netflix provides Feign as an abstraction over REST-based calls, by which microservices 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 communicated with EmployeeService, we programmatically constructed the URL of the dependent microservice, then called the service using RestTemplate, so we need to be aware of the RestTemplate API to communicate with other microservices, which is certainly not part of our business logic.

The question is, why should a developer have to know the details of a REST API? Microservice developers only concentrate on business logic, so Spring addresses this issues and comes with Feign Client, which works on the declarative principle. We have to create an interface/contract, then Spring creates the original implementation on the fly, so a REST-based service call is abstracted from developers. Not only that — if you want to customize the call, like encoding your request or decoding the response in a Custom Object, you can do it with Feign in a declarative way. Feign, as a client, is an important tool for microservice developers to communicate with other microservices via Rest API.

Coding Time

Here, we will alter our EmployeeDashboard Service to make it Feign-enabled.

Step 1: We will add the 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 we want to call. Please note that Service Request mapping is same as the EmployeeSearch Service Rest URL. Feign will call this URL when we call the EmployeeDashBoard service.

Feign dynamically generates the implementation of the interface we created, so Feign has to know which service to call beforehand. That's why we need to give a name for the interface, which is the {Service-Id} of EmployeeService. Now, Feign contacts the Eureka server with this Service Id, resolves the actual IP/hostname of the EmployeeService, and calls the URL provided in Request Mapping.

N.B.: When using @PathVariable for Feign Client, always use value property or 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 autowire our Interface so Spring can Inject actual implementation during runtime. Then, we call that implementation to call the 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 scan its annotation. For this, we need to add the @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 to 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 the browser.

You will see the 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"
   }
]


Discover how to deploy pre-built sample microservices OR create simple microservices from scratch.

Topics:
microservices ,rest ,tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}