Created
February 23, 2021 14:56
-
-
Save dalexandrov/7569a53201ea385d33bb51bf6c3a7c4f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Readiness | |
@ApplicationScoped | |
public class Neo4jHealthCheck implements HealthCheck { | |
private static final String CYPHER = "RETURN 1 AS result"; | |
private static final SessionConfig DEFAULT_SESSION_CONFIG = SessionConfig.builder() | |
.withDefaultAccessMode(AccessMode.WRITE) | |
.build(); | |
private final Driver driver; | |
@Inject | |
//will be ignored outside of CDI | |
Neo4jHealthCheck(Driver driver) { | |
this.driver = driver; | |
} | |
public static Neo4jHealthCheck create(Driver driver) { | |
return new Neo4jHealthCheck(driver); | |
} | |
private static HealthCheckResponse buildStatusUp(ResultSummary resultSummary, HealthCheckResponseBuilder builder) { | |
ServerInfo serverInfo = resultSummary.server(); | |
builder.withData("server", serverInfo.version() + "@" + serverInfo.address()); | |
String databaseName = resultSummary.database().name(); | |
if (!(databaseName == null || databaseName.trim().isEmpty())) { | |
builder.withData("database", databaseName.trim()); | |
} | |
return builder.build(); | |
} | |
@Override | |
public HealthCheckResponse call() { | |
HealthCheckResponseBuilder builder = HealthCheckResponse.named("Neo4j connection health check").up(); | |
try { | |
ResultSummary resultSummary; | |
// Retry one time when the session has been expired | |
try { | |
resultSummary = runHealthCheckQuery(); | |
} catch (SessionExpiredException sessionExpiredException) { | |
resultSummary = runHealthCheckQuery(); | |
} | |
return buildStatusUp(resultSummary, builder); | |
} catch (Exception e) { | |
return builder.down().withData("reason", e.getMessage()).build(); | |
} | |
} | |
private ResultSummary runHealthCheckQuery() { | |
// We use WRITE here to make sure UP is returned for a server that supports | |
// all possible workloads | |
if (driver != null) { | |
Session session = this.driver.session(DEFAULT_SESSION_CONFIG); | |
Result run = session.run(CYPHER); | |
return run.consume(); | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment