Different Ways to Establish Communication Between Spring Microservices
Last Updated : 30 Jan, 2022
If you are working with a Spring Boot project which involves multiple microservices, You might have felt the need to communicate from microservice m1 to microservice m2. Depending upon business use-cases, this communication can be of synchronous or asynchronous type. Before digging dip further. Let's understand the use-case first. There are two microservices:
- Restaurant-Service: Responsible for maintaining items being served by a restaurant, processing orders, etc.
- User-Service: Responsible for maintaining user details.
Now suppose a user visits a restaurant's page, selects some cuisine of his choice and clicks on the "Place Order" button. When this request lands in restaurant-service, the service would want to validate user details before processing this order. But our user details lie under user-service. Hence here comes the need to communicate from restaurant-service to user-service. Synchronous communication of m2 from m1 is like calling an API of m2 directly from m1.
Synchronous Way
When we talk about synchronous communication, there could be two ways:
- REST Template
- Feign
REST Template
REST Template is the easiest way to establish synchronous communication from m1 to m2. RestTemplate is a class available under spring.framework.web.client that acts as a synchronous client to perform HTTP requests. In the below example, we have used getForEntity method that accepts complete URL of the user-service that we want to invoke, followed by Data-Object class name which that URL is supposed to return, and a map. If the provided userId is not valid, the API call would throw a custom exception which we are handing on the restaurant-service side.
Java HashMap<String, Long> params = new HashMap<>(); params.put("userId", orderDetails.getUserId()); try { ResponseEntity<User> response = new RestTemplate().getForEntity( "http://localhost:8080/users/{userId}", User.class, params); } catch (Exception ex) { throw new InvalidUserIdException( "User Id " + orderDetails.getUserId() + " Not Found"); }
Feign
Feign requires additional configuration across both services if you want to go by this way. This approach uses standard Java interfaces. Addition perks of using feign over rest-template is that you don't get to hard-code your URL here. Eureka Client ID can also be used for server-discovery purposes in order to establish communication.
Asynchronous Way
One possible asynchronous way to establish communication is by using a message broker. Let's understand the use-case first.
Considering the microservices discussed above, let's suppose a user has placed his order. Now the order would go under various stages like Accepted, Preparation-Started, Ready-To-Pick, Delivered. Assuming all the stages of the order would be updated by the restaurant-service, we want to notify user-service every time the order-status is updated. Now this can be achieved either way but the asynchronous way would be more convenient here.
- Message-Broker: It behaves as an intermediary service between m1 and m2. When m1 has to communicate with m2, m1 would push a message to the broker instead of directly sending it to the m2. Depending on the broker's type (ActiveMQ and Kafka are two popular message-brokers but they have different approaches of communication), the message will be conveyed to the listener of m2 and action would be taken accordingly. Here m1 would be known as producer while m2 would be known as consumer.
Similar Reads
How to create a basic application in Java Spring Boot Spring Boot is the most popular Java framework that is used for developing RESTful web applications. In this article, we will see how to create a basic Spring Boot application.Spring Initializr is a web-based tool using which we can easily generate the structure of the Spring Boot project. It also p
3 min read
How to Create a REST API using Java Spring Boot? Representational State Transfer (REST) is a software architectural style that defines a set of constraints for creating web services. RESTful web services allow systems to access and manipulate web resources through a uniform and predefined set of stateless operations. Unlike SOAP, which exposes its
4 min read
Easiest Way to Create REST API using Spring Boot Spring Boot is a powerful framework that makes it easy to create RESTful APIs. Creating a REST API using Spring Boot is one of the fastest and simplest ways to develop scalable and production-ready web services. Spring Boot simplifies REST API development by providing built-in features such as autom
10 min read
Java Spring Boot Microservices Sample Project Microservices are more popular nowadays. They can be written in any language. In this article, let us see Spring Boot Microservices. in this article let us see a base project "currency-exchange-sample-service" which has a business logic and which can be invoked in another project "currency-conversio
9 min read
Difference between Spring MVC and Spring Boot 1. Spring MVC : Spring is widely used for creating scalable applications. For web applications Spring provides Spring MVC framework which is a widely used module of spring which is used to create scalable web applications. Spring MVC framework enables the separation of modules namely Model View, Con
3 min read
Spring Boot - Spring JDBC vs Spring Data JDBC Understanding the difference between Spring JDBC and Spring Data JDBC is important for choosing the right approach to interact with relational databases in Spring Boot applications. Both frameworks serve the same purpose but differ significantly in terms of abstraction, ease of use, and developer pr
5 min read
Best Practices For Structuring Spring Boot Application Spring Boot is built on top of the conventional spring framework. So, it provides all the features of spring and is yet easier to use than spring. In this article, we are going to see how one should start and structure his Spring Boot application. Prerequisites: Good knowledge of Java.Basic knowledg
3 min read
Spring Boot - Start/Stop a Kafka Listener Dynamically In a Spring Boot application, Kafka Listeners start automatically once the application launches and they listen for messages from Kafka topics. But there are many scenarios where we might need to dynamically start or stop a Kafka listener based on certain conditions. This can be achieved using Kafka
6 min read
How To Dockerize A Spring Boot Application With Maven ? Docker is an open-source containerization tool that is used for building, running, and managing applications in an isolated environment. It facilitates the developers to bundles its software, libraries, and configuration files. The Docker facilitates with isolating the one container from another. In
12 min read
Dynamic Dropdown From Database using Spring Boot The concept of dynamic dropdown (or dependent dropdown) is exciting and challenging to code. Dynamic dropdown means that the values in one dropdown list are dependent on the value selected in the previous dropdown list. A simple example would be three dropdown boxes displaying names of the district,
11 min read