Spring web application healthchecks
amazon-web-services, java, spring
Solution
I'd suggest using health checks functionality from Metrics. You could set up a number of classes that extend `HealthCheck` class and implement `check()` method. These health check implementations would be Spring managed beans themselves and could autowire Spring beans and validate them. Then configure `HealthCheckServlet` to monitor application state. Also check metrics-spring project. It will make Spring and Metrics integration simpler.
If you are using Java Spring configuration you might have a Metrics config like this that extends `MetricsConfigurerAdapter` from metrics-spring
@Configuration
@EnableMetrics
public class MetricsConfig extends MetricsConfigurerAdapter { }
And then `@Import(value = {MetricsConfig.class})` to your Spring config.
You also need and implementation of `ServletContextListener` to wire up `HealthCheckServlet` and Spring. This `HealthCheckContextListener` should be added to your `web.xml`
public class HealthCheckContextListener extends
HealthCheckServlet.ContextListener implements ServletContextListener {
private WebApplicationContext context;
public HealthCheckContextListener(WebApplicationContext context) {
this.context = context;
}
public HealthCheckContextListener() {}
@Override
public void contextInitialized(ServletContextEvent event) {
this.context = WebApplicationContextUtils.getRequiredWebApplicationContext(event.getServletContext());
event.getServletContext().setAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY,
context.getBean(HealthCheckRegistry.class));
}
@Override
protected HealthCheckRegistry getHealthCheckRegistry() {
return (HealthCheckRegistry) context.getBean(HealthCheckRegistry.class);
}
}
Problem
I'm deploying Spring based web applications on Amazon's Beanstalk platform, and they give me the option of setting a "healthcheck" URL path for my application. The idea is that their platform will do a request against that URL, after the deployment, to see if the application is successfully started. So, if the request results in an HTTP 200, the application is probably fine. But if it results in an HTTP 500 or something else, the platform knows there's a problem with the application. So, I wish I could develop some kind of servlet that would check if the Spring Application Context was successfully initialised, or not, to give an appropriate HTTP response code to the platform. Has anybody attempted something like this? For similar purposes? I'm wondering if Spring already provides some elegant solution for this.