Rubia
Rubia

Reputation: 467

spring boot application periodic post request via resttemplate in json

Below is my spring boot code snippet to post json data to server url every few min to tell that I am alive and running(which loads my json input data to db). purpose of this post request is to update the status on application monitoring tool.

What could be the right approach to implment this behaviour in my spring boot app? Is their any decorator api to do such post request to url, every few miuntes through out the application.? how can I know the time of successful post request to do next post request ? Please help me. Thanks in advance.

RestTemplate restTemplate = new RestTemplate();
String url = "endpoint url";
String requestJson = "{\"I am alive\":\"App name?\"}";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers);
String answer = restTemplate.postForObject(url, entity, String.class);
System.out.println(answer);

Upvotes: 0

Views: 795

Answers (1)

Dovmo
Dovmo

Reputation: 8739

Why don't you use the @Scheduled annotation? This will seutes.nd your REST request every 3 minutes...

@Component
public class Heartbeater {

    @Scheduled(fixedDelay = 180000)
    public void heartbeat() {
        // Your code is below...
        RestTemplate restTemplate = new RestTemplate();
        String url = "endpoint url";
        String requestJson = "{\"I am alive\":\"App name?\"}";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers);
        String answer = restTemplate.postForObject(url, entity, String.class);
        System.out.println(answer);
}

Upvotes: 2

Related Questions