DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Breaking Up a Monolithic Database with Kong
  • REST Services With Apache Camel
  • User-Friendly API Publishing and Testing With Retrofit
  • Diving Deep Into REST API Channels

Trending

  • Architecting Petabyte-Scale Hyperspectral Pipelines on AWS
  • Stop Writing Dialect-Specific SQL: A Unified Query Builder for Node.js
  • Evaluating SOC Effectiveness Using Detection Coverage and Response Metrics
  • When Perfect Data Breaks: The Journey from Data Quality to Data Observability
  1. DZone
  2. Data Engineering
  3. Data
  4. Microservices Communication: Feign as REST Client

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.

By 
Shaamik Mitraa user avatar
Shaamik Mitraa
·
May. 27, 18 · Tutorial
Likes (18)
Comment
Save
Tweet
Share
227.8K Views

Join the DZone community and get the full member experience.

Join For Free

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"
   }
]


microservice REST Web Protocols

Published at DZone with permission of Shaamik Mitraa. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Breaking Up a Monolithic Database with Kong
  • REST Services With Apache Camel
  • User-Friendly API Publishing and Testing With Retrofit
  • Diving Deep Into REST API Channels

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook