INTRODUCTION
We are learning about the communication between two microservices. how microservices interact with one another and call the API of other microservices.
There are two types of microservices communication.
1) Synchronous communication.
2) Asynchronous communication.
1) Synchronous communication :
The client delivers a request to the service using synchronous communication, then waits for a response. The crucial aspect of this situation is that the HTTP/HTTPS protocol is synchronous, meaning that the client code can only carry out its operation after receiving the HTTP server answer. The advantages of synchronous communication in microservices include the ease of request-response exchanges, real-time data transmission, and simple error management.
2) Asynchronous communication :
In the context of microservices, asynchronous communication is the exchange of messages or requests between various microservices without necessitating a prompt response. In other words, the sender does not wait for a prompt response before sending a message to the recipient.
Microservices Communication using RestTemplate :
We have created two microservices employee-service and department-service. We will make rest-API call using Rest Template and fetch other microservice data.
We will have separate project and database configuration for both the projects.
Creating department-service in spring boot.
Step 1 : Create a department service project using spring initializr
Step 2 : Add required dependency in pom.xml of project.
Step 3 : Configure database in application.properties file.
spring.datasource.url=jdbc:mysql://localhost:3306/department
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=update
Simply include the information above in your application.properties document. You don't have to manually construct the database, spring.jpa.hibernate.ddl-auto=update You can use it to automatically construct the database.
Step 4 : Create DTO class which is Department :
import javax.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Entity
@Table(name = "departments")
@NoArgsConstructor
@AllArgsConstructor
@Setter
@Getter
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String departmentName;
private String departmentAddress;
}
Step 5 : Create Spring JPA Repository :
import org.springframework.data.jpa.repository.JpaRepository;
public interface DepartmentRepository extends JpaRepository<Department, Long> {
}
Step 6 : Create a Service Layer :
public interface DepartmentService {
Department getDepartmentById(Long departmentId);
}
@Service
@AllArgsConstructor
@Slf4j
public class DepartmentServiceImpl implements DepartmentService {
@Override
public Department getDepartmentById(Long departmentId) {
return departmentRepository.findById(departmentId).get();
}
}
Step 7 : Create a Controller layer
@RestController
@RequestMapping("api/departments")
@AllArgsConstructor
public class DepartmentController {
private DepartmentService departmentService;
@GetMapping("{id}")
public ResponseEntity<Department> getDepartmentById
(@PathVariable("id") Long departmentId){
Department department= departmentService.getDepartmentById(departmentId);
return ResponseEntity.ok(department);
}
}
Step 8 : Run the main class and application is run at port number 8080.
Creating Employee-service in Spring Boot
Step 1 : Creating employee-service project using spring initializr
Step 2 : Add required dependency in pom.xml of project
Step 3 : Add database configuration in application.properties file.
spring.datasource.url=jdbc:mysql://localhost:3306/employee
spring.datasource.username=root
spring.datasource.password=root1
spring.jpa.hibernate.ddl-auto=update
Also need to change the port number of project so you can add
server.port= 8081
Step 4 : Create DTO class which is Employee :
import javax.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Entity
@Table(name = "Employee")
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class Employee{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String employeeName;
private String employeeEmailId;
private String departmentId;
}
Step 5 : Create Spring Data Repository which employeeRepository :
import org.springframework.data.jpa.repository.JpaRepository;
public interface EmployeeRepository extends JpaRepository<
Employee, Long> {
}
Step 6 : Create DTO classes for Reponse.
DepartmentDTO.class
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class DepartmentDTO {
private Long id;
private String departmentName;
private String departmentAddress;
}
EmployeeDTO class
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class EmployeeDTO {
private Long id;
private String employeeName;
private String employeeEmail;
}
ReponseDTO class
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class ResponseDTO {
public DepartmentDTO deparment;
public EmployeeDTO employee
}
Step 7 : Configure RestTemplate as bean in main class.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class EmployeeServiceApplication {
public static void main(String[] args) {
SpringApplication.run(EmployeeServiceApplication.class, args);
}
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
Step 8 : Create a Service Layer :
public interface EmployeeService {
ResponseDto getEmployee(Long employeeId);
}
@Service
@AllArgsConstructor
public class EmployeeServiceImpl implements EmployeeService {
private EmployeeRepository employeeRepository;
private RestTemplate restTemplate;
@Override
public ResponseDto getEmployee(Long employeeId) {
ResponseDto responseDto = new ResponseDto();
Employee employee = employeeRepository.findById(employeeId).get();
EmployeeDTO employeeDto = mapDetailsToUser(employee);
ResponseEntity<DepartmentDto> responseEntity =
restTemplate
.getForEntity("http://localhost:8080/api/departments/"
+ user.getDepartmentId(),
DepartmentDTO.class);
DepartmentDTO departmentDto = responseEntity.getBody();
System.out.println(responseEntity.getStatusCode());
responseDto.setemployee(employeedto);
responseDto.setDepartment(departmentDto);
return responseDto;
}
private EmployeeDTO mapDetailsToUser(Employee employee){
EmployeeDTO employeeDto = new EmployeeDTO();
employeeDto.setId(employee.getId());
employeedto.setFirstName(employee.getEmployeeName());
employeedto.setEmail(employee.getEmployeeEmail());
return employeedto;
}
}
Step 9 : Create a controller layer
@RestController
@RequestMapping("api/employee")
@AllArgsConstructor
public class EmployeeController {
private EmployeeService employeeService;
@GetMapping("{id}")
public ResponseEntity<ResponseDto>
getEmployee(@PathVariable("id") Long employeeId){
ResponseDTO responseDto = employeeService.getEmployee(employeeId);
return ResponseEntity.ok(responseDto);
}
}
Step 10 : Run the employee-service application having port number 8081.
Conclusion :
In this lesson, we learned how to use a RestTemplate to call one microservice to another microservice. However, because it is deprecated, Spring advises using Webclient instead, which can support both sync and async circumstances.
0 Comments
Post a Comment