![]() |
VOOZH | about |
Spring Cloud is a collection of projects like load balancing, service discovery, circuit breakers, routing, micro-proxy, etc will be given by Spring Cloud. So spring Cloud basically provides some of the common tools and techniques and projects to quickly develop some common patterns of the microservices.
Basically, there are two ways to load balance the request
If you are keeping the load balancer on the client side and giving the load balancing responsibility to the client, then we called it Client-Side Load Balancing. And Spring Cloud LoadBalancer is one of the most popular client-side load balancers provided by Spring Cloud.
Note: Please refer to this article Spring Cloud - Load Balancer
The Spring Cloud Load Balancer library permits us to create applications that communicate with other applications in a load-balanced fashion. Using any algorithm we want, we can easily execute load balancing when making remote service calls.
How to Use Spring Cloud LoadBalancer?
Add the following dependency in your pom.xml file
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
Let's see the whole implementation by developing 2 Microservices and 1 Service Discovery. In brief, Client Side Load Balancing can happen with the help of LoadBalancerClient. You have to write the following logic in your client microservice inside the Service class.
@Autowired
private RestTemplate restTemplate;
@Autowired
private LoadBalancerClient loadBalancerClient;
// Get ServiceInstance list using serviceId
ServiceInstance serviceInstance = loadBalancerClient.choose("ADDRESS-SERVICE");
// Read URI and Add path that returns url
String uri = serviceInstance.getUri().toString();
// Get metadata
String contextPath = serviceInstance.getMetadata().get("configPath");
// Make HTTP call and get Response data
AddressResponse addressResponse = restTemplate.getForObject(uri + contextPath + "/address/{id}", AddressResponse.class, id);
Please refer to this article and develop a service discovery: Java Spring Boot Microservices - Developing Service Discovery.
Step 1: Create a New Spring Boot Project in Spring Initializr
To create a new Spring Boot project, please refer to How to Create a Spring Boot Project in Spring Initializr and Run it in IntelliJ IDEA. For this project choose the following things
Please choose the following dependencies while creating the project.
Generate the project and run it in IntelliJ IDEA by referring to the above article.
Note: We have used the MySQL database in this project.
Step 2: Create Schema in MySQL Workbench and Put Some Sample Data
Go to your MySQL Workbench and create a schema named gfgmicroservicesdemo and inside that create a table called address and put some sample data as shown in the below image.
Address Table:
Here we have created 4 columns and put some sample data.
Note: In the Address table, employee_id is a foreign key so create it accordingly. We are going to perform a SQL join operation in our native SQL query. So create tables carefully.
Before moving to IntelliJ IDEA let's have a look at the complete project structure for our Microservices.
Step 3: Make Changes in Your application.properties File
Now make the following changes in your application.properties file.
spring.datasource.url=jdbc:mysql://localhost:3306/gfgmicroservicesdemo
spring.datasource.username=put your username here
spring.datasource.password=put your password here
spring.application.name=address-service
server.port=8081
server.servlet.context-path=/address-service
eureka.instance.metadata-map.configPath=/address-service
Step 4: Create Your Entity/Model Class
Go to the src > main > java > entity and create a class Address and put the below code. This is our model class.
Step 5: Create Your Repository Interface
Go to the src > main > java > repository and create an interface AddressRepo and put the below code. This is our repository where we write code for all the database-related stuff.
Note: Please refer to this article to know more about JpaRepository.
Step 6: Create an AddressResponse Class
Go to the src > main > java > response and create a class AddressResponse and put the below code.
Step 7: Create Your Service Class
Go to the src > main > java > service and create a class AddressService and put the below code. This is our service class where we write our business logic.
Step 8: Create an Address Controller
Go to the src > main > java > controller and create a class AddressController and put the below code. Here we are going to create an endpoint "/address/{employeeId}" to find the address using employee_id. Thats why we have created a foreign key in the Address table and we have performed the SQL join operation in the native query to get our desired result.
Step 9: Create a Configuration Class
Go to the src > main > java > configuration and create a class AddressConfig and put the below code.
Note: You may refer to these two articles
Before running the Microservice below is the complete pom.xml file. Please cross-verify if you have missed some dependencies
Step 1: Create a New Spring Boot Project in Spring Initializr
To create a new Spring Boot project, please refer to How to Create a Spring Boot Project in Spring Initializr and Run it in IntelliJ IDEA. For this project choose the following things
Please choose the following dependencies while creating the project.
Generate the project and run it in IntelliJ IDEA by referring to the above article.
Note: We have used the MySQL database in this project.
Step 2: Create Schema in MySQL Workbench and Put Some Sample Data
Go to your MySQL Workbench and create a schema named gfgmicroservicesdemo and inside that create a table called employee and put some sample data as shown in the below image. Here we have created 4 columns and put some sample data.
👁 Spring-Boot-Microservices-1-(2)
Now we are going to fetch Employee Data from Employee Table in our Spring Boot project. To do it refer to the following steps. Before moving to IntelliJ IDEA let's have a look at the complete project structure for our Microservices.
Step 3: Make Changes in Your application.properties File
Now make the following changes in your application.properties file.
spring.datasource.url=jdbc:mysql://localhost:3306/gfgmicroservicesdemo
spring.datasource.username=put your username here
spring.datasource.password=put your password here
spring.application.name=employee-service
server.port=8080
# Set Your Context Path Here
server.servlet.context-path=/employee-service
You may also refer to the below image:
Step 4: Create Your Entity/Model Class
Go to the src > main > java > entity and create a class Employee and put the below code. This is our model class.
Step 5: Create Your Repository Interface
Go to the src > main > java > repository and create an interface EmployeeRepo and put the below code. This is our repository where we write code for all the database-related stuff.
Note: Please refer to this article to know more about JpaRepository.
Step 6: Create an EmployeeResponse Class
Go to the src > main > java > response and create a class EmployeeResponse and put the below code.
Step 7: Create Your Service Class
Go to the src > main > java > service and create a class EmployeeService and put the below code. This is our service class where we write our business logic.
Step 8: Create an Employee Controller
Go to the src > main > java > controller and create a class EmployeeController and put the below code. Here we are going to create an endpoint "/employees/{id}" to find an employee using id.
Step 9: Create a Configuration Class
Go to the src > main > java > configuration and create a class EmployeeConfig and put the below code.
Note: You may refer to these two articles
Before running the Microservice below is the complete pom.xml file. Please cross-verify if you have missed some dependencies
Now run your both Address and Employee Microservices along with your Discovery Service. If everything goes well then you may see the following screen in your Eureka dashboard. Please refer to the below image.
Now open Postman and hit the following URL
GET: http://localhost:8080/employee-service/employees/2
And you can see the following response
{
"id": 2,
"name": "Asish",
"email": "asis@gmail",
"age": "30",
"addressResponse": {
"id": 1,
"city": "BLS",
"state": "Odisha"
}
}
Please refer to the below image.
👁 microservice-communication-3