Thursday, November 22, 2018

Spring Boot (Microservice) - Inter service call

Generally, inter service call more common, when we develop a microservice application. So in this artical, I'm going to explain, how to use RestTemplate to call another service.

We have eurekaServer, zuulServer, clientServer, serverServer. Initially, we need to register our all servers with the eurekaServer.
zuulServer register as proxyService
clientServer register as oneService
serverServer register as twoService

twoService has a end-point as below:
http method: PUT
url: /api/person/{personId}/bank

this end-point is going to update the bank information in particulate person and we need to pass the bank details in the body. As below, you can call above end-point in twoService from oneService.

    @Autowired 
    private final RestTemplate restTemplate;
    @Autowired 
    private final EurekaClient eurekaClient;
   .....
   .....
    public CustomResponseMessageDTO method() {
     ....
        String endPoint = "/api/person/{personId}/bank"
        HttpEntity<BankDTO> requestEntity = new HttpEntity<>(bank_information_BankDTO_object);
        Map<String, String> param = new HashMap<>();
param.put("personId", "person_id_should_pass");
        Application application = eurekaClient.getApplication(twoService);
        InstanceInfo instanceInfo = application.getInstances().get(0);
        String url = "http://" + instanceInfo.getIPAddr() + ":" + instanceInfo.getPort() + endPoint;
        ResponseEntity<CustomResponseMessageDTO> exchange = restTemplate.exchange(url, HttpMethod.PUT, requestEntity, CustomResponseMessageDTO.class, param);
        return exchange.getBody(); // this return the CustomResponseMessageDTO object.
    }
....
As above, you can pass the message body using HttpEntity and url paramerter using HashMap.

If you need to pass the header you can add the header to the HttpEntity as below
HttpEntity<BankDTO> requestEntity = new HttpEntity<>(bank_information_BankDTO_object, HttpHeaders_object);

Enjoy..!!!

Spring Boot - Read yml file

When developing a Spring Boot application, we are using yml (properties) file to store the data. Due to this without we don't want to re-build the source code after change the property values.

Even thought this a very basic thing, in this article, I'm going to explain the way we can get the data from yml file.

For this explanation, I'm going to take application.yml file and we have a property as below
company:
  name: Company ABC

Then we can get this value in java code as below
public class TestApplication {
...
@Value("${company.name}")
        private String companyName;
...
}

This value will cast to the variable type.

Enjoy.....!!!