每天學點SpringCloud(十):SpringCloud監控

今天我們來學習一下actuator這個組件,它不是SpringCloud之後纔有的,而是SpringBoot的一個starter,Spring Boot Actuator。我們使用SpringCloud的時候需要使用這個組件對應用程序進行監控與管理

在SpringBoot2.0版本中,actuator可以爲我們提供以下端點:

訪問路徑描述
/actuator/auditevents顯示當前應用程序的審計事件信息
/actuator/beans顯示一個應用中所有Spring Beans的完整列表
/actuator/conditions顯示配置類和自動配置類的狀態及它們被應用或未被應用的原因
/actuator/configprops顯示一個所有@ConfigurationProperties的集合列表
/actuator/env顯示來自Spring的 ConfigurableEnvironment的屬性
/actuator/features顯示系統啓動的一些features
/actuator/health顯示應用的健康信息
/actuator/httptrace最後100個HTTP請求
/actuator/info顯示任意的應用信息
/actuator/metrics展示當前應用的metrics信息
/actuator/mappings顯示一個所有@RequestMapping路徑的集合列表
/actuator/refresh更新配置
/actuator/scheduledtasks顯示應用程序中的定時任務
/actuator/service-registry當前應用在註冊中心的狀態
/actuator/shutdown允許應用以優雅的方式關閉
/actuator/threaddump執行一個線程dump
/actuator/heapdump返回一個GZip壓縮的hprof堆dump文件
/actuator/loggers返回系統的一些日誌

雖然actuator默認給我們提供了這麼多的端點供我們使用,但是爲了安全起見,在SpringBoot2.0中它僅僅開放了health和info兩個端口,如果想要使用其他的端口就需要我們增加一些配置了,一起來看一下如何使用actuator吧。

1. 引入依賴

1
2
3
4
<dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-actuator</artifactId>
      </dependency>

2. 修改配置文件

1
2
3
4
5
6
management:
 endpoints:
   web:
     exposure:
       #exclude: shutdown,threaddump   #此處控制的是不開放哪些端點
       include: "*" #此處控制的是開放哪些端點,如果需要開啓少數端點可以這樣配置:health,info。如果開啓多個則使用*號開啓除了exclude的端點

這個時候我們使用postman等接口調用工具訪問 ip:端口/actuator 這個路徑時就會得到下圖所示的這麼一個json串,這個json串中就是對應的各個端點的地址信息。
1

3. 健康檢查

默認我們訪問/actuator/health得到的只是一個狀態值,其實它的詳細信息裏包含了很多有用的東西,比如說檢查磁盤空間、DataSource的連接、Elasticsearch、Mongo、Rabbit、Redis等信息,我們可以通過如下配置來開啓詳細的健康檢查:

1
2
3
4
management:
 endpoint:
   health:
     show-details: always

不僅如此,健康檢查的指標我們還可以自定義,創建如下的一個bean提供健康檢查的功能。

1
2
3
4
5
6
7
8
9
10
11
12
@Component
public class ConnectTimeHealthIndicator implements HealthIndicator {
   @Override
   public Health health() {
       long connectTime=(long)Math.random()*10;//模擬一個連接操作
       if(connectTime>3){
           //如果連接時間大於3則認爲連接失敗,返回狀態爲down
           return Health.down().withDetail("code", "504").withDetail("msg","xx應用連接超時").build();
       }
       return Health.up().build();
   }
}

此時我們訪問 ip:端口/actuator/health 訪問時可能就會根據連接時間呈現下方的兩種狀態
2
3

GitHub地址:https://github.com/shiyujun/spring-cloud-demo。代碼所在模塊:cloud-demo-consumer-feign

如果對您有所幫助,請記得幫忙點一個star哦

本文出自http://zhixiang.org.cn,轉載請保留。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章