首頁(yè) 資訊 Spring Boot Actuator自定義健康檢查教程

Spring Boot Actuator自定義健康檢查教程

來源:泰然健康網(wǎng) 時(shí)間:2025年06月04日 18:06

Java技術(shù)迷

健康檢查是Spring Boot Actuator中重要端點(diǎn)之一,可以非常容易查看應(yīng)用運(yùn)行至狀態(tài)。本文在前文的基礎(chǔ)上介紹如何自定義健康檢查。

1. 概述

本節(jié)我們簡(jiǎn)單說明下依賴及啟用配置,展示缺省健康信息。首先需要引入依賴:

1

compile("org.springframework.boot:spring-boot-starter-actuator")

現(xiàn)在通過http://localhost:8080/actuator/health端點(diǎn)進(jìn)行驗(yàn)證:

缺省該端點(diǎn)返回應(yīng)用中很多組件的匯總健康信息,但可以修改屬性配置展示詳細(xì)內(nèi)容:

1

2

3

4

management:

  endpoint:

    health:

      show-details: always

現(xiàn)在再次訪問返回結(jié)果如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

{

  "status": "UP",

  "components": {

    "diskSpace": {

      "status": "UP",

      "details": {

        "total": 214748360704,

        "free": 112483500032,

        "threshold": 10485760,

        "exists": true

      }

    },

    "ping": {

      "status": "UP"

    }

  }

}

查看DiskSpaceHealthIndicatorProperties文件的源碼:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

@ConfigurationProperties(prefix = "management.health.diskspace")

public class DiskSpaceHealthIndicatorProperties {

 /**

  * Path used to compute the available disk space.

  */

 private File path = new File(".");

 /**

  * Minimum disk space that should be available.

  */

 private DataSize threshold = DataSize.ofMegabytes(10);

 public File getPath() {

  return this.path;

 }

 public void setPath(File path) {

  this.path = path;

 }

 public DataSize getThreshold() {

  return this.threshold;

 }

 public void setThreshold(DataSize threshold) {

  Assert.isTrue(!threshold.isNegative(), "threshold must be greater than or equal to 0");

  this.threshold = threshold;

 }

}

上面結(jié)果顯示當(dāng)前項(xiàng)目啟動(dòng)的路徑 . ,報(bào)警值 為10M ,這些屬性都可以通過配置進(jìn)行修改。

2. 預(yù)定義健康指標(biāo)

上面Json響應(yīng)顯示“ping”和“diskSpace”檢查。這些檢查也稱為健康指標(biāo),如果應(yīng)用引用了數(shù)據(jù)源,Spring會(huì)增加db健康指標(biāo);同時(shí)“diskSpace”是缺省配置。

Spring Boot包括很多預(yù)定義的健康指標(biāo),下面列出其中一部分:

DataSourceHealthIndicator MongoHealthIndicator Neo4jHealthIndicator CassandraHealthIndicator RedisHealthIndicator CassandraHealthIndicator RabbitHealthIndicator CouchbaseHealthIndicator DiskSpaceHealthIndicator (見上面示例) ElasticsearchHealthIndicator InfluxDbHealthIndicator JmsHealthIndicator MailHealthIndicator SolrHealthIndicator

如果在Spring Boot應(yīng)用中使用Mongo或Solr等,則Spring Boot會(huì)自動(dòng)增加相應(yīng)健康指標(biāo)。

3. 自定義健康指標(biāo)

Spring Boot提供了一捆預(yù)定義健康指標(biāo),但并沒有阻止你增加自己的健康指標(biāo)。一般有兩種自定義類型檢查:

單個(gè)健康指標(biāo)組件和組合健康指標(biāo)組件。

3.1 自定義單個(gè)指標(biāo)組件

自定義需要實(shí)現(xiàn)HealthIndicator接口并重新health()方法,同時(shí)增加@Component注解。假設(shè)示例應(yīng)用程序與服務(wù)A(啟動(dòng))和服務(wù)B(關(guān)閉)通信。如果任一服務(wù)宕機(jī),應(yīng)用程序?qū)⒈灰暈殄礄C(jī)。因此,我們將寫入兩個(gè)運(yùn)行狀況指標(biāo)。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

@Component

public class ServiceAHealthIndicator implements HealthIndicator {

    private final String message_key = "Service A";

    @Override

    public Health health() {

        if (!isRunningServiceA()) {

            return Health.down().withDetail(message_key, "Not Available").build();

        }

        return Health.up().withDetail(message_key, "Available").build();

    }

    private Boolean isRunningServiceA() {

        Boolean isRunning = true;

        return isRunning;

    }

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

@Component

public class ServiceBHealthIndicator implements HealthIndicator {

    private final String message_key = "Service B";

    @Override

    public Health health() {

        if (!isRunningServiceB()) {

            return Health.down().withDetail(message_key, "Not Available").build();

        }

        return Health.up().withDetail(message_key, "Available").build();

    }

    private Boolean isRunningServiceB() {

        Boolean isRunning = false;

        return isRunning;

    }

}

現(xiàn)在,我們看到健康監(jiān)控響應(yīng)中增加的指標(biāo)。ServerA狀態(tài)是UP,ServiceB是DOWN,因此整個(gè)監(jiān)控檢測(cè)狀態(tài)為DOWN.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

{

  "status": "DOWN",

  "components": {

    "diskSpace": {

      "status": "UP",

      "details": {

        "total": 214748360704,

        "free": 112483229696,

        "threshold": 10485760,

        "exists": true

      }

    },

    "ping": {

      "status": "UP"

    },

    "serviceA": {

      "status": "UP",

      "details": {

        "Service A": "Available"

      }

    },

    "serviceB": {

      "status": "DOWN",

      "details": {

        "Service B": "Not Available"

      }

    }

  }

}

3.2 自定義組合健康檢查

前面示例很容易查看各個(gè)指標(biāo)各自的狀態(tài)。但有時(shí)需要基于幾個(gè)指標(biāo)查看資源的狀態(tài),則需要使用 HealthContributor ,該接口沒有定義方法,僅用于標(biāo)記。如果一個(gè)服務(wù)有另外兩個(gè)動(dòng)作組合進(jìn)行實(shí)現(xiàn),只有兩者同時(shí)工作該服務(wù)狀態(tài)才算正常。最后使用 CompositeHealthContributors組合多個(gè)指標(biāo):

1

2

3

4

public class ServiceAHealthIndicator

    implements HealthIndicator, HealthContributor {

...

}

下面定義組合健康檢查指標(biāo):

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

@Component("UserServiceAPI")

public class UserServiceAPIHealthContributor

    implements CompositeHealthContributor {

  private Map<String, HealthContributor>

          contributors = new LinkedHashMap<>();

  @Autowired

  public UserServiceAPIHealthContributor(

      ServiceAHealthIndicator serviceAHealthIndicator, ServiceBHealthIndicator serviceBHealthIndicator) {

    contributors.put("serverA",  serviceAHealthIndicator);

    contributors.put("serverB", serviceBHealthIndicator);

  }

  /**

   *  return list of health contributors

   */

  @Override

  public Iterator<NamedContributor<HealthContributor>> iterator() {

    return contributors.entrySet().stream()

       .map((entry) -> NamedContributor.of(entry.getKey(), entry.getValue())).iterator();

  }

  @Override

  public HealthContributor getContributor(String name) {

    return contributors.get(name);

  }

}

現(xiàn)在我們使用serverA和serverB組合新的檢查UserServiceAPI。

4. 總結(jié)

本文我們學(xué)習(xí)了Spring Boot健康指標(biāo)及相關(guān)配置、以及預(yù)定義的健康指標(biāo),同時(shí)介紹了如何自定義健康指標(biāo)。

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

您可能感興趣的文章:

關(guān)于Spring Cloud健康檢查的陷阱springboot 如何禁用某項(xiàng)健康檢查SpringBoot Admin健康檢查功能的實(shí)現(xiàn)詳解SpringBoot健康檢查的實(shí)現(xiàn)原理Spring Cloud Admin健康檢查 郵件、釘釘群通知的實(shí)現(xiàn)SpringBoot實(shí)現(xiàn)項(xiàng)目健康檢查與監(jiān)控SpringBoot actuator 健康檢查不通過的解決方案

原文鏈接:https://blog.csdn.net/neweastsun/article/details/108933365

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。
如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)將相關(guān)資料發(fā)送至 reterry123@163.com 進(jìn)行投訴反饋,一經(jīng)查實(shí),立即處理!

相關(guān)知識(shí)

spring boot 應(yīng)用在 k8s 中的健康檢查(一)
spring 健康檢查地址
如何為SpringBoot應(yīng)用設(shè)置健康檢查
如何關(guān)閉nacos健康檢查
Eureka自我保護(hù)機(jī)制、健康檢查的作用、actuator模塊監(jiān)控
SpringBoot之旅
揭秘微服務(wù)健康檢查:如何保障系統(tǒng)穩(wěn)定運(yùn)行的關(guān)鍵一步
詳解 Spring Boot 2.7.18 與 MyBatis PageHelper 的整合步驟
Nacos如何查看集群節(jié)點(diǎn)健康狀態(tài)?
健康檢查 檢測(cè)java假死

網(wǎng)址: Spring Boot Actuator自定義健康檢查教程 http://www.u1s5d6.cn/newsview1365992.html

推薦資訊