"Welcome To Ashok IT" "Spring Boot and MicroServices" Topic : MicroServices Communication Date : 24/01/2025 (Session - 109) _____________________________________________________________________________________________________________________________ Yesterday Session ================= * We have been Completed developing Address Microservices Today Session ============== * After completing the developing the Customer-Service & Address-Service * Now We have requirement to pull the Customer Information along with associated Address Information. * We required to communicate from One Microservices to another Microservice using RestTemplate,WebClient,FeignClient * Following are the below endpoints required code changes for Customer-Service endpoints 1) Get Customer By ID 2) Get All Customers CustomerService.java ==================== package com.ashokit.services; import java.util.List; import com.ashokit.request.CustomerRequest; import com.ashokit.response.ApiResponse; import com.ashokit.response.CustomerResponse; public interface CustomerService { public CustomerResponse createCustomer(CustomerRequest customerRequest); public CustomerResponse getCustomerById(Integer customerId); public ApiResponse getCustomerAndAddressById(Integer customerId); public List getAllCustomers(); } CustomerServiceImpl.java ======================== package com.ashokit.services; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; import org.springframework.core.ParameterizedTypeReference; import org.springframework.core.env.Environment; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import org.springframework.web.reactive.function.client.WebClient; import com.ashokit.dao.CustomerDao; import com.ashokit.entity.Customer; import com.ashokit.feign.clients.AddressClient; import com.ashokit.request.CustomerRequest; import com.ashokit.response.AddressResponse; import com.ashokit.response.ApiResponse; import com.ashokit.response.CustomerResponse; @Service public class CustomerServiceImpl implements CustomerService { @Autowired private CustomerDao customerDao; @Autowired private ModelMapper modelMapper; @Autowired private RestTemplate restTemplate; @Value("${address.service.name.url}") public String addressServiceUrl; @Autowired public WebClient webClient; @Autowired private Environment environment; @Override public CustomerResponse createCustomer(CustomerRequest customerRequest) { //converting from CustomerRequest To Entity Class Object Customer customer = convertingFromRequestToEntity(customerRequest); //Saving Customer Information Customer savedCustomer = this.customerDao.save(customer); //Converting From Customer Entity to CustomerResponse Object return this.convertingEntityFromResponse(savedCustomer); } @Override public CustomerResponse getCustomerById(Integer customerId) { Optional customerDetails = this.customerDao.findById(customerId); if (customerDetails.isPresent()) { Customer custDetails = customerDetails.get(); CustomerResponse customerResponse = this.convertingEntityFromResponse(custDetails); //calling the AddressService AddressResponse addressResponse = callingAddressServiceWithRestTemplate(customerId); //Appending AddressResponse to CustomerResponse(1st Technique) customerResponse.setAddressResponse(addressResponse); return customerResponse; }else { //throw the exception return null; } } @Override public ApiResponse getCustomerAndAddressById(Integer customerId) { Optional customerDetails = this.customerDao.findById(customerId); if (customerDetails.isPresent()) { Customer custDetails = customerDetails.get(); CustomerResponse customerResponse = this.convertingEntityFromResponse(custDetails); //calling the AddressService //AddressResponse addressResponse = callingAddressServiceWithRestTemplate(customerId); AddressResponse addressResponse = callingAddressServiceWithWebClient(customerId); //Appending CustomerResponse & AddressResponse to ApiResponse(2nd Technique) ApiResponse apiResponse = new ApiResponse(); //setting values apiResponse.setCustomerDetails(customerResponse); apiResponse.setAddressDetails(addressResponse); return apiResponse; }else { //throw the exception return null; } } @Override public List getAllCustomers() { //Getting All Customers Details List allCustomers = this.customerDao.findAll(); //converting from List into List List allCustomerResponse = allCustomers.stream() .map(eachCustomer -> {return this.modelMapper.map(eachCustomer, CustomerResponse.class);}) .collect(Collectors.toList()); //Writing logic for Address Microservices to get All Address and map to each customer //List allAddressResponse = callingAddressServiceForAllAddressWithRestTemplate(); //List allAddressResponse = callingAddressServiceForAllAddressWithWebClient(); List allAddressResponse = addressClient.fetchAllAddresses().getBody(); //Mapping the Address with Customer List allCustomerResponse1 = allCustomerResponse.stream() .map(eachCustomer -> { Optional add = allAddressResponse.stream() .filter(eachAddress ->{ return eachAddress.getCustomerId() == eachCustomer.getId(); }) .findAny(); //setting AddressResponse to CustomerResponse eachCustomer.setAddressResponse(add.get()); return eachCustomer; }) .collect(Collectors.toList()); //returning CustomerResponse return allCustomerResponse1; } //utility method for converting customerRequest to Entity Object private Customer convertingFromRequestToEntity(CustomerRequest customerRequest) { Customer customer = modelMapper.map(customerRequest,Customer.class); System.out.println("Customer::::" + customer); return this.modelMapper.map(customerRequest,Customer.class); } //utility method for converting customerRequest to Entity Object private CustomerResponse convertingEntityFromResponse(Customer customer) { CustomerResponse custResponse = this.modelMapper.map(customer,CustomerResponse.class); System.out.println("CustomerResponse::::" + custResponse.getCreatedDate()); return custResponse; } //calling the Address micro service to Fetch Address of particular Customer private AddressResponse callingAddressServiceWithRestTemplate(int customerId) { System.out.println("Address Service URL:::" + addressServiceUrl); ResponseEntity addressResponseEntity = restTemplate.getForEntity(addressServiceUrl+"customer/{customerId}", AddressResponse.class, customerId ); //By Using exchange() of RestTemplate /*ResponseEntity addressResponseEntity = restTemplate.exchange(addressServiceUrl+"{customerId}", HttpMethod.GET, null, AddressResponse.class, customerId);*/ //checking the API Status if(addressResponseEntity.getStatusCode() == HttpStatus.OK) { //ResponseBody of API if(addressResponseEntity.hasBody()) { return addressResponseEntity.getBody(); } } return null; } //calling the Address micro service to Fetch Address of particular Customer private AddressResponse callingAddressServiceWithWebClient(int customerId) { AddressResponse addressResponse = webClient.get() .uri("customer/"+customerId) .retrieve() .bodyToMono(AddressResponse.class) .block(); return addressResponse; } //calling the Address micro service to Fetch Address of particular Customer private List callingAddressServiceForAllAddressWithRestTemplate() { ResponseEntity> addressResponseEntity = restTemplate.exchange(addressServiceUrl, HttpMethod.GET, null, new ParameterizedTypeReference>(){}); //checking the API Status if(addressResponseEntity.getStatusCode() == HttpStatus.OK) { //ResponseBody of API if(addressResponseEntity.hasBody()) { return addressResponseEntity.getBody(); } } return null; } //calling the Address micro service to Fetch Address of particular Customer private List callingAddressServiceForAllAddressWithWebClient() { List allAddress = webClient.get() .accept(MediaType.APPLICATION_JSON) .retrieve() .bodyToMono(new ParameterizedTypeReference>(){}) .block(); return allAddress; } } +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++