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.
twoService has a end-point as below:
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.
If you need to pass the header you can add the header to the HttpEntity as below
Enjoy..!!!
We have eurekaServer, zuulServer, clientServer, serverServer. Initially, we need to register our all servers with the eurekaServer.
zuulServer register as proxyServiceclientServer register as oneServiceserverServer register as twoService
twoService has a end-point as below:
http method: PUTurl: /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.
@AutowiredAs above, you can pass the message body using HttpEntity and url paramerter using HashMap.
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.}....
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..!!!
No comments:
Post a Comment