SpringBoot組件Actuator數(shù)據(jù)源判活源碼

背景說明

在生產(chǎn)環(huán)境中,需要實時或定期監(jiān)控服務(wù)的可用性。Spring Boot的actuator(健康監(jiān)控)功能提供了很多監(jiān)控所需的接口,可以對應(yīng)用系統(tǒng)進行配置查看、相關(guān)功能統(tǒng)計等。

這里針對Actuator組件對數(shù)據(jù)源[DataSource]判活進行源碼閱讀簡要過程進行記錄。

解決方案

組件引入

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

主類入口

1.X請閱讀org.springframework.boot.actuate.health.DataSourceHealthIndicator
2.X 請閱讀org.springframework.boot.actuate.jdbc.DataSourceHealthIndicator

核心流程

由于1.X2.X在核心邏輯上并沒有變化,只是對包名做了調(diào)整,這里針對2.X進行閱讀分析,當我們需要對我們新建的一個模塊進行健康監(jiān)控的話,可以把這些監(jiān)控信息統(tǒng)一歸納到health節(jié)點下,只需要實現(xiàn)HealthIndicator接口即可,當我們調(diào)用health端口獲取監(jiān)控狀態(tài)時health方法會自動執(zhí)行。

@FunctionalInterface
public interface HealthIndicator {

   /**
    * Return an indication of health.
    * @return the health for
    */
   Health health();

}

HealthIndicator-健康檢查指示器

查看源碼AbstractHealthIndicator的核心實現(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的核心實現(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是默認判活SQL當通過數(shù)據(jù)庫廠商無法獲取到對應(yīng)的SQL時會使用此默認的SQL,當數(shù)據(jù)庫不支持此默認SQL時會出現(xiàn)判活失敗即報錯的情況。

由此可以看出核心流程如下:

獲取數(shù)據(jù)源廠商=>獲取判活SQL=>執(zhí)行判活SQL=>構(gòu)建返回內(nèi)容

分支流程

構(gòu)建JdbcTemplate

通過數(shù)據(jù)源新建一個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"),
}

這里維護了數(shù)據(jù)庫廠商和判活SQL的映射,當通過數(shù)據(jù)庫廠商名稱沒有找到時返回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);

暴露端點

1.X

如果僅僅想關(guān)閉數(shù)據(jù)源安全檢查可以使用配置managent.health.db.enable=false關(guān)閉

management.port=8088

默認情況下健康檢查和應(yī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

默認情況下健康檢查和應(yīng)用端口一致,可以使用配置項management.server.port=8088更改端口
默認情況下端點服務(wù)暴露,需要通過management.endpoints.web.exposure.include進行開啟,如果需要排除可以使用management.endpoints.web.exposure.exclude進行排除即可
默認情況下無法暴露明細數(shù)據(jù),可以通過配置項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)置了健康檢查功能,打開控制臺后,右側(cè)有一個端點包含Bean、運行狀況、映射,當數(shù)據(jù)源檢查不通過時,Idea控制會出現(xiàn)異常日志,例如當數(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)
............................................................
............................................................
............................................................
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容