Skip to content

Instantly share code, notes, and snippets.

@pdtyreus
Created May 7, 2015 21:40
Show Gist options
  • Save pdtyreus/7d0bde27a7b211aa76df to your computer and use it in GitHub Desktop.
Save pdtyreus/7d0bde27a7b211aa76df to your computer and use it in GitHub Desktop.
Simple Dropwizard HealthCheck for a Neo4j server
import com.codahale.metrics.health.HealthCheck;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import javax.ws.rs.core.MediaType;
public class Neo4jHealthCheck extends HealthCheck {
private final String serviceRoot = "/db/data/";
private String expectedVersion = null;
private final String urlString;
private final Client client;
public Neo4jHealthCheck(Client client, String host, int port) {
StringBuilder urlStringBuilder = new StringBuilder();
urlStringBuilder.append("http://");
urlStringBuilder.append(host);
urlStringBuilder.append(":");
urlStringBuilder.append(port);
urlStringBuilder.append(serviceRoot);
this.client = client;
urlString = urlStringBuilder.toString();
}
public Neo4jHealthCheck(Client client, String host, int port, String expectedVersion) {
this(client, host, port);
this.expectedVersion = expectedVersion;
}
@Override
protected Result check() throws Exception {
RootResponse response = client.resource(urlString).accept(MediaType.APPLICATION_JSON).get(RootResponse.class);
if (response == null) {
return Result.unhealthy("Null response from Neo4j at " + urlString);
}
if (expectedVersion != null) {
if (!expectedVersion.equals(response.neo4jVersion)) {
return Result.unhealthy("Expected Neo4j version " + expectedVersion + " but found " + response.neo4jVersion);
}
}
return Result.healthy();
}
@JsonIgnoreProperties(ignoreUnknown = true)
private static class RootResponse {
@JsonProperty("neo4j_version")
private String neo4jVersion;
}
}
@pdtyreus
Copy link
Author

pdtyreus commented May 7, 2015

For anyone using Dropwizard in conjunction with the REST-based interface of a Neo4j graph database server, this is a simple HealthCheck implementation.

If you're running Neo4j as an HA cluster, you'll probably want to modify the endpoints to test as described in the HA documentation.

To create the Jersey Client instance to pass in to the constructor, you will want to add dropwizard-client to your project and configure as described.

The end result might look like

  final Client jerseyClient = new JerseyClientBuilder(environment).using(config.getJerseyClientConfiguration()).build(getName());
  environment.healthChecks().register("neo4j", new Neo4jHealthCheck(jerseyClient, config.getNeo4j().getHostName(), config.getNeo4j().getPort(), "2.2.1"));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment