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 Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  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.

Shamik Mitra user avatar by
Shamik Mitra
·
May. 27, 18 · Tutorial
Like (18)
Save
Tweet
Share
222.56K 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 Shamik Mitra, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Stop Using Spring Profiles Per Environment
  • Introduction to Spring Cloud Kubernetes
  • Tracking Software Architecture Decisions
  • Building a Real-Time App With Spring Boot, Cassandra, Pulsar, React, and Hilla

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: