Add database query defaults in SimpleHealthManager

pull/184/head
Dave Syer 11 years ago
parent 063403a043
commit 8e2a6eec2a

@ -18,6 +18,7 @@ package org.springframework.boot.actuate.health;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
@ -37,16 +38,27 @@ public class SimpleHealthIndicator implements HealthIndicator<Map<String, Object
private JdbcTemplate jdbcTemplate;
private String query = "SELECT 'Hello'";
private static Map<String, String> queries = new HashMap<String, String>();
static {
queries.put("HSQL Database Engine",
"SELECT COUNT(*) FROM INFORMATION_SCHEMA.SYSTEM_USERS");
queries.put("Oracle", "SELECT 'Hello' from DUAL");
queries.put("Apache Derby", "SELECT 1 FROM SYSIBM.SYSDUMMY1");
}
private static String DEFAULT_QUERY = "SELECT 'Hello'";
private String query = null;
@Override
public Map<String, Object> health() {
LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
map.put("status", "ok");
String product = "unknown";
if (this.dataSource != null) {
try {
String product = this.jdbcTemplate
.execute(new ConnectionCallback<String>() {
product = this.jdbcTemplate.execute(new ConnectionCallback<String>() {
@Override
public String doInConnection(Connection connection)
throws SQLException, DataAccessException {
@ -59,10 +71,11 @@ public class SimpleHealthIndicator implements HealthIndicator<Map<String, Object
map.put("status", "error");
map.put("error", ex.getClass().getName() + ": " + ex.getMessage());
}
if (StringUtils.hasText(this.query)) {
String query = detectQuery(product);
if (StringUtils.hasText(query)) {
try {
map.put("hello",
this.jdbcTemplate.queryForObject(this.query, String.class));
this.jdbcTemplate.queryForObject(query, String.class));
}
catch (Exception ex) {
map.put("status", "error");
@ -73,6 +86,17 @@ public class SimpleHealthIndicator implements HealthIndicator<Map<String, Object
return map;
}
protected String detectQuery(String product) {
String query = this.query;
if (!StringUtils.hasText(query)) {
query = queries.get(product);
}
if (!StringUtils.hasText(query)) {
query = DEFAULT_QUERY;
}
return query;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplate = new JdbcTemplate(dataSource);

@ -51,7 +51,6 @@ public class SimpleHealthIndicatorTests {
@Test
public void database() {
this.indicator.setDataSource(this.dataSource);
this.indicator.setQuery("SELECT count(*) FROM INFORMATION_SCHEMA.SYSTEM_TABLES");
Map<String, Object> health = this.indicator.health();
assertNotNull(health.get("database"));
assertNotNull(health.get("hello"));

Loading…
Cancel
Save