What is the FeignClient?

Yasin Memiç
3 min readJan 14, 2022

--

FeignClient helps us to communicate between two services. By the way, this need can also handle with RestTemplate, etc. but feignClient has some advantages and it‘s more preferred with microservices. Using RestTemplate has some disadvantages like the following:

1- Too many lines of code for each connection.

2- Duplication of code with no business logic.

FeignClient was developed by Netflix. It makes writing web service clients easier.

One of the advantages is that we don’t have to know any implementation. It’s enough just to use an interface.

How to include FeignClient into our project?

First off, we should add the following dependency.

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

After that, we should add @EnableFeignClient to use FeignClient. The following image is an example.

Example

I have a really basic example for explaining. Let’s start with the pom.xml

I’ll use dependencies that are lombok, spring-boot-starter-web, and spring-cloud-starter-openfeign.

Like I said before, we need to add @EnableFeignClients annotation to enable FeignClient.

After that, I’ll create an interface for defining a feignClient. Also, the following link will be the target service. We’ll communicate with the following service. https://jsonplaceholder.typicode.com/

The Post class will be the response that returns from jsonplaceholderService. In this way, we also have a model to return as JSON.

Let’s create our controller class:

Notice that, we can use directly jsonPlaceHolderClient. We don’t have to know any information about jsonPlaceHolderClient implementation.

Let’s send a request by Postman. The first request will be the get-posts request. I showed the response that return from our service below, as well.

Likewise, we can send a request for a specific id with the “posts/{id}” service.

As a result, using FeignClient is a different way to communicate between microservices. It can be used as needed.

--

--