I have a microservice based on spring boot. I have a spring cloud configserver as well in-place. So depending upon the changes in the configserver microservice restart automatically.
So now i need to grab the timestamp when the application got restarted.
Is it possible to do so in the same microservice?
CodePudding user response:
You can listen to spring events such as the ContextStartedEvent. There's a tutorial here that lays it out:
@EventListener
public void handleContextStartedEvent(ContextStartedEvent ctxStartEvt) {
System.out.println("Context Start Event received.");
}
CodePudding user response:
yes, possible by adding the actuator and enabling the startup endpoint.
step1: Add the below dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<version>2.5.4</version>
</dependency>
step2: Add the below property into the application.properties files.
management.endpoints.web.exposure.include=startup
step3: Setup a little amount of buffer memory to store the startup info and it won't affect the performance at anywhere in your application.
@SpringBootApplication
public class StartupTrackingApplication {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(StartupTrackingApplication.class);
app.setApplicationStartup(new BufferingApplicationStartup(2048));
app.run(args);
}
}
step: Hit the below URL using CURL like below or a POST call from POSTMAN. Then you will be seeing all startup-related info like when the startup started and ended. e.t.c.
curl 'http://localhost:8080/actuator/startup' -X POST | jq
For more explanation, view reference
In the response json, node "timeline"."startTime" is the exact startup timestamp when the applicant has started its startup job.