背景說明
在生產(chǎn)環(huán)境中剃氧,需要實(shí)時(shí)或定期監(jiān)控服務(wù)的可用性。Spring Boot的actuator(健康監(jiān)控)功能提供了很多監(jiān)控所需的接口阻星,可以對(duì)應(yīng)用系統(tǒng)進(jìn)行配置查看朋鞍、相關(guān)功能統(tǒng)計(jì)等。
這里針對(duì)Actuator組件對(duì)數(shù)據(jù)源[DataSource]判活進(jìn)行源碼閱讀簡要過程進(jìn)行記錄。
解決方案
組件引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
主類入口
1.X
請(qǐng)閱讀org.springframework.boot.actuate.health.DataSourceHealthIndicator
2.X
請(qǐng)閱讀org.springframework.boot.actuate.jdbc.DataSourceHealthIndicator
核心流程
由于1.X
和2.X
在核心邏輯上并沒有變化滥酥,只是對(duì)包名做了調(diào)整更舞,這里針對(duì)2.X
進(jìn)行閱讀分析,當(dāng)我們需要對(duì)我們新建的一個(gè)模塊進(jìn)行健康監(jiān)控的話,可以把這些監(jiān)控信息統(tǒng)一歸納到health節(jié)點(diǎn)下恨狈,只需要實(shí)現(xiàn)HealthIndicator接口即可,當(dāng)我們調(diào)用health端口獲取監(jiān)控狀態(tài)時(shí)health方法會(huì)自動(dòng)執(zhí)行疏哗。
@FunctionalInterface
public interface HealthIndicator {
/**
* Return an indication of health.
* @return the health for
*/
Health health();
}
HealthIndicator
-健康檢查指示器
查看源碼AbstractHealthIndicator
的核心實(shí)現(xiàn)
public abstract class AbstractHealthIndicator implements HealthIndicator {
@Override
public final Health health() {
Health.Builder builder = new Health.Builder();
try {
doHealthCheck(builder);
}
catch (Exception ex) {
if (this.logger.isWarnEnabled()) {
String message = this.healthCheckFailedMessage.apply(ex);
this.logger.warn(StringUtils.hasText(message) ? message : DEFAULT_MESSAGE,
ex);
}
builder.down(ex);
}
return builder.build();
}
protected abstract void doHealthCheck(Health.Builder builder) throws Exception;
}
查看DataSourceHealthIndicator
的核心實(shí)現(xiàn)
public class DataSourceHealthIndicator extends AbstractHealthIndicator implements InitializingBean {
private static final String DEFAULT_QUERY = "SELECT 1";
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
if (this.dataSource == null) {
builder.up().withDetail("database", "unknown");
}
else {
doDataSourceHealthCheck(builder);
}
}
private void doDataSourceHealthCheck(Health.Builder builder) throws Exception {
String product = getProduct();
builder.up().withDetail("database", product);
String validationQuery = getValidationQuery(product);
if (StringUtils.hasText(validationQuery)) {
// Avoid calling getObject as it breaks MySQL on Java 7
List<Object> results = this.jdbcTemplate.query(validationQuery,
new SingleColumnRowMapper());
Object result = DataAccessUtils.requiredSingleResult(results);
builder.withDetail("hello", result);
}
}
}
這里
DEFAULT_QUERY
是默認(rèn)判活SQL
當(dāng)通過數(shù)據(jù)庫廠商無法獲取到對(duì)應(yīng)的SQL
時(shí)會(huì)使用此默認(rèn)的SQL
,當(dāng)數(shù)據(jù)庫不支持此默認(rèn)SQL
時(shí)會(huì)出現(xiàn)判活失敗即報(bào)錯(cuò)的情況禾怠。
由此可以看出核心流程如下:
獲取數(shù)據(jù)源廠商=>獲取判活SQL
=>執(zhí)行判活SQL
=>構(gòu)建返回內(nèi)容
分支流程
構(gòu)建JdbcTemplate
通過數(shù)據(jù)源新建一個(gè)JdbcTemplate
用于數(shù)據(jù)查詢
public DataSourceHealthIndicator(DataSource dataSource, String query) {
super("DataSource health check failed");
this.dataSource = dataSource;
this.query = query;
this.jdbcTemplate = (dataSource != null) ? new JdbcTemplate(dataSource) : null;
}
獲取數(shù)據(jù)源廠商
private String getProduct() {
return this.jdbcTemplate.execute((ConnectionCallback<String>) this::getProduct);
}
private String getProduct(Connection connection) throws SQLException {
return connection.getMetaData().getDatabaseProductName();
}
這里返回的數(shù)據(jù)廠商可能為MySQL
返奉,PostgreSQL
,Oracle
等
獲取數(shù)據(jù)源判活SQL
protected String getValidationQuery(String product) {
String query = this.query;
if (!StringUtils.hasText(query)) {
DatabaseDriver specific = DatabaseDriver.fromProductName(product);
query = specific.getValidationQuery();
}
if (!StringUtils.hasText(query)) {
query = DEFAULT_QUERY;
}
return query;
}
這里關(guān)注類org.springframework.boot.jdbc.DatabaseDriver
,源碼摘錄部分如下
public enum DatabaseDriver {
UNKNOWN((String)null, (String)null),
MYSQL("MySQL", "com.mysql.jdbc.Driver", "com.mysql.jdbc.jdbc2.optional.MysqlXADataSource", "/* ping */ SELECT 1"),
MARIADB("MySQL", "org.mariadb.jdbc.Driver", "org.mariadb.jdbc.MariaDbDataSource", "SELECT 1") {
public String getId() {
return "mysql";
}
},
ORACLE("Oracle", "oracle.jdbc.OracleDriver", "oracle.jdbc.xa.client.OracleXADataSource", "SELECT 'Hello' from DUAL"),
POSTGRESQL("PostgreSQL", "org.postgresql.Driver", "org.postgresql.xa.PGXADataSource", "SELECT 1"),
}
這里維護(hù)了數(shù)據(jù)庫廠商和判活SQL
的映射,當(dāng)通過數(shù)據(jù)庫廠商名稱沒有找到時(shí)返回UNKNOWN
public static DatabaseDriver fromProductName(String productName) {
if (StringUtils.hasLength(productName)) {
DatabaseDriver[] var1 = values();
int var2 = var1.length;
for(int var3 = 0; var3 < var2; ++var3) {
DatabaseDriver candidate = var1[var3];
if (candidate.matchProductName(productName)) {
return candidate;
}
}
}
return UNKNOWN;
}
構(gòu)建返回結(jié)果
Object result = DataAccessUtils.requiredSingleResult(results);
builder.withDetail("hello", result);
暴露端點(diǎn)
1.X
如果僅僅想關(guān)閉數(shù)據(jù)源安全檢查可以使用配置managent.health.db.enable=false
關(guān)閉
management.port=8088
默認(rèn)情況下健康檢查和應(yīng)用端口一致吗氏,可以使用配置項(xiàng)
management.port=8088
更改端口
訪問接口:http://localhost:8088/actuator/health
2.X
如果僅僅想關(guān)閉數(shù)據(jù)源安全檢查可以使用配置management.health.db.enabled=false
關(guān)閉
management.server.port=8088
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always
默認(rèn)情況下健康檢查和應(yīng)用端口一致芽偏,可以使用配置項(xiàng)
management.server.port=8088
更改端口
默認(rèn)情況下端點(diǎn)服務(wù)暴露,需要通過management.endpoints.web.exposure.include
進(jìn)行開啟弦讽,如果需要排除可以使用management.endpoints.web.exposure.exclude
進(jìn)行排除即可
默認(rèn)情況下無法暴露明細(xì)數(shù)據(jù)污尉,可以通過配置項(xiàng)management.endpoint.health.show-details
暴露
健康檢查
86183@LAPTOP-CRFFK470 MINGW64 ~
$ curl -X GET http://localhost:8088/actuator/health
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 189 0 189 0 0 12600 0 --:--:-- --:--:-- --:--:-- 12600{"status":"UP","details":{"db":{"status":"UP","details":{"database":"MySQL","hello":1}},"diskSpace":{"status":"UP","details":{"total":808121790464,"free":9833570304,"threshold":10485760}}}}
86183@LAPTOP-CRFFK470 MINGW64 ~
$
例外情況
Idea旗艦版本內(nèi)置了健康檢查功能,打開控制臺(tái)后往产,右側(cè)有一個(gè)端點(diǎn)包含Bean被碗、運(yùn)行狀況、映射仿村,當(dāng)數(shù)據(jù)源檢查不通過時(shí)锐朴,Idea控制會(huì)出現(xiàn)異常日志,例如當(dāng)數(shù)據(jù)庫廠商為Calcite
at org.springframework.boot.actuate.health.DataSourceHealthIndicator.doDataSourceHealthCheck(DataSourceHealthIndicator.java:109)
at org.springframework.boot.actuate.health.DataSourceHealthIndicator.doceHealthCheck(DataSourceHealthIndicator.java:98)
at org.springframework.boot.actuate.health.AbstractHealthIndicator.health(AbstractHealthIndicator.java:43)
............................................................
............................................................
............................................................
at org.springframework.boot.actuate.health.DataSourceHealthIndicator.doDataSourceHealthCheck(DataSourceHealthIndicator.java:109)
at org.springframework.boot.actuate.health.DataSourceHealthIndicator.doceHealthCheck(DataSourceHealthIndicator.java:98)
at org.springframework.boot.actuate.health.AbstractHealthIndicator.health(AbstractHealthIndicator.java:43)
............................................................
............................................................
............................................................