1. 程式人生 > >spring-boot-actuator學習總結和思考

spring-boot-actuator學習總結和思考

      自定義健康指示器時,需要實現HealthIndicator,重寫health()方法即可。呼叫withDetail()方法向健康記錄裡新增其他附加資訊。有多個附加資訊時,可多次呼叫withDetail()方法,每次設定一個健康記錄的附加欄位。

示例(關於一個異常的健康指示器)如下:

@Componentpublic 
class CustomHealth implements HealthIndicator{   
 @Override   
 public Health health() {   
     try {        
         RestTemplate restTemplate = new
RestTemplate(); restTemplate.getForObject("http://localhost:8080/index",String.class); return Health.up().build(); }catch (Exception e){ return Health.down().withDetail("down的原因:",e.getMessage()).build(); } } }

 執行“http://localhost:8080/health


之後就會出現一些列健康指示。有時候有的瀏覽器僅僅出現{"status":"DOWN"},為什麼會是這樣呢?官網給了我們答案

Shows application health information (when the application is secure, a simple ‘status’ when accessed over an unauthenticated connection or full message details when authenticated)
而且要求Sensitive Default 為flase

5. 更改健康檢查埠

預設情況下健康檢查埠和app埠是使用同一個,如我們之前使用的,但是為了安全起見、不影響業務我們最好使用另外的埠進行健康檢查,如使用9090

埠,在application.properties檔案中設定management.port=9090

6.跨域訪問的支援

預設情況下是不支援對actuator端點的跨域訪問,假如我們在一個統一的監控平臺下希望支援跨域呼叫這些端點來指向相應的操作,則需要作如下的配置。

Cross-origin resource sharing (CORS) is a W3C specification that allows you to specify in a flexible way what kind of cross domain requests are authorized. Actuator’s MVC endpoints can be configured to support such scenarios.

CORS support is disabled by default and is only enabled once the endpoints.cors.allowed-origins property has been set. The configuration below permitsGET and POST calls from the  domain:

endpoints.cors.allowed-origins=http://example.com
endpoints.cors.allowed-methods=GET,POST

7.已經進行自動配置的HealthIndicators

The following HealthIndicators are auto-configured by Spring Boot when appropriate:

It is possible to disable them all using the management.health.defaults.enabled property.

8.通過Remote-Shell來進行監控和管理

Spring Boot supports an integrated Java shell called ‘CRaSH’. You can use CRaSH to ssh or telnet into your running application. To enable remote shell support, add the following dependency to your project:

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

The remote shell is deprecated and will be removed in Spring Boot 2.0.

If you want to also enable telnet access you will additionally need a dependency on org.crsh:crsh.shell.telnet.

CRaSH requires to run with a JDK as it compiles commands on the fly. If a basic help command fails, you are probably running with a JRE.

三. 專案應用現狀和思考

        目前只有hotel.pms.admin該服務應用到了該框架,只是針對不同的環境做了啟用和不啟用的相關配置,並沒有做太多針對專案實際情況的應用。例如:

         1.所有的啟動檢測介面可以使用健康檢查是否有效的判斷,訪問http://host:port/health的地址,並在所有專案內鋪開。

         2.針對所有應用的監控,都可以新增autuator的相關配置,方便在線上出現和資源消耗相關的問題時,可以對問題進行初步的排查,並瞭解系統資源相關的第一手資訊。

         3.通過bean相關的分析,可以對無效的相關包引用進行排除。畢竟多載入一個包也是對資源的一個浪費。

         4.通過info資訊來顯示服務端應用的最新資訊以瞭解釋出的最新版本。

四.總結

        建議在Q2開始推動在所有的後端服務內推廣嵌入actuator相關的配置,以保障服務基礎配置的標準化。