Spring Boot and OpenFeign — Communication Between Microservices

Spring internal microservice-driven communication

ELATTAR Saad
Better Programming

--

During the solution architecture phase, especially when we’re talking microservices, we need a sort of internal exchange of data. There are many tools to do so, such as Spring rest template and web client, but I’m using the one I find the simplest of them all: Yes, OpenFeign!

Installing OpenFeign

First, we add the OpenFeign dependency (inside the pom.xml file), so it will be imported by Maven (our dependency manager).

As you already noticed, we are using a tool that belongs to the Spring cloud project, as result, we need to set the Spring cloud version we’re using. Inside the properties tag, we’ll add both: java and spring cloud versions:

Please note that I’m using the Spring boot version 2.6.1
Also, note that I'll be using the movies project from the previous articles.

After having all the needed dependencies, we still have to declare our app is using OpenFeign in a certain package.

We decorate our main class with the @EnableFeignClients with the target package which will have the feign clients.

OpenFeign client implementation

In the implementation, I will be sending a simple get request to the JSON placeholder API (acting as the second micro-service) to get a list of posts using OpenFeign:

Defining our DTO

In order to make use of the JSON/POJO auto-conversion that Spring Boot offers, we’ll be using a DTO to manipulate the received/sent data (posts).
Inside the controller > dto package, we create the PostDTO.java file:

Note that the structure of the DTO is defined by the response of the JSON placeholder API.

Next, we create our post client (feign client), which is going to be like the following:

@FeignClient will declare this interface as a feign client in order to be implemented according to our needs.

The name attribute is mainly useless in this case since we're not addressing the API with a name, but using its URL instead. The name is used when a naming registry is integrated (a future article is on the way).

And just like magic, that's all for our client!

Now we need to call our client and return the response to our user. We'll create a PostController that does just that:

Finally, that's what you will get when invoking this PostController method:

Thanks for reading.

--

--

Warm regards! I'm Saad, a software engineer. The most enjoyable part of any journey is what you share along the way, so code and document the journey!