SpringBoot 開啓 Actuator

在生產環境中,須要實時或按期監控服務的可用性。spring-boot 的actuator(監控)功能提供了不少監控所需的接口。簡單的配置和使用以下:html


一、引入依賴:java

[html] view plain copy
 
  1. <dependency>  
  2.     <groupId>org.springframework.boot</groupId>  
  3.     <artifactId>spring-boot-starter-actuator</artifactId>  
  4. </dependency>  


若是使用http調用的方式,還須要這個依賴:git

[html] view plain copy
 
  1. <dependency>  
  2.     <groupId>org.springframework.boot</groupId>  
  3.     <artifactId>spring-boot-starter-web</artifactId>  
  4. </dependency>  


二、配置:github

application.yml中指定監控的HTTP端口(若是不指定,則使用和server相同的端口):web

 

management:
  port: 54001
  # close security. 關閉身份驗證,不然沒法查詢出數據
  security:
    enabled: false

 

三、使用:spring

查看health指標:http://localhost:54001/health數據庫

[plain] view plain copy
 
  1. {"status":"UP","diskSpace":{"status":"UP","total":120031539200,"free":33554337792,"threshold":10485760},"db":{"status":"UP","dataSource1":{"status":"UP","database":"MySQL","hello":1},"dataSource2":{"status":"UP","database":"MySQL","hello":1}}}  


四、自定義指標:
4.1 /health:在某個類中implements HealthIndicator接口,而後實現其中的health()方法便可:安全

代碼:app

 

[java] view plain copy
 
  1. @SpringBootApplication  
  2. @EnableScheduling  
  3. public class MySpringBootApplication implements HealthIndicator{  
  4.     private static Logger logger = LoggerFactory.getLogger(MySpringBootApplication.class);  
  5.       
  6.     public static void main(String[] args) {  
  7.         SpringApplication.run(MySpringBootApplication.class, args);  
  8.         logger.info("My Spring Boot Application Started");  
  9.     }  
  10.   
  11.     /** 
  12.      * 在/health接口調用的時候,返回多一個屬性:"mySpringBootApplication":{"status":"UP","hello":"world"} 
  13.      */  
  14.     @Override  
  15.     public Health health() {  
  16.         return Health.up().withDetail("hello", "world").build();  
  17.     }  
  18. }  

/health 運行結果(注意第二個指標):ide

{"status":"UP","mySpringBootApplication":{"status":"UP","hello":"world"},"diskSpace":{"status":"UP","total":120031539200,"free":33554337792,"threshold":10485760},"db":{"status":"UP","dataSource1":{"status":"UP","database":"MySQL","hello":1},"dataSource2":{"status":"UP","database":"MySQL","hello":1}}}

 

4.2 /info:配置以下,能夠直接給一個字符串,也能夠從pom.xml配置中獲取

 

[plain] view plain copy
 
  1. info:  
  2.   app:  
  3.     name: "@project.name@" #從pom.xml中獲取  
  4.     description: "@project.description@"  
  5.     version: "@project.version@"  
  6.     spring-boot-version: "@project.parent.version@"  

/info的結果以下:

 

 

{"app":{"name":"my-spring-boot","description":"Test Project for Spring Boot","version":"1.0","spring-boot-version":"1.3.6.RELEASE"}}

 

 

官網:http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#production-ready

源代碼參考:https://github.com/xujijun/my-spring-boot

 

 

----------------------------

 

 

異常狀況:
 
 
 
  1. /health 只有status信息,沒有其餘
 
  
  1. {
  2. "status" : "UP"
  3. }
 
  
  1. /metrics 提示沒有權限
 
  
  1. Whitelabel Error Page
  2. This application has no explicit mapping for /error, so you are seeing this as a fallback.
  3. Mon Nov 20 10:42:15 CST 2017
  4. There was an unexpected error (type=Unauthorized, status=401).
  5. Full authentication is required to access this resource.
 
 
解決辦法【設置端點訪問 】:
 
  • 方式1-關閉驗證 
 
  
  1. application.properties添加配置參數
  2. management.security.enabled=false
  • 方式2-開啓HTTP basic認證 
    • 添加依賴    
 
  
  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-security</artifactId>
  4. </dependency>
  • application.properties 添加用戶名和密碼
 
   
  1. security.user.name=admin
  2. security.user.password=123456
  3. management.security.enabled=true
  4. management.security.role=ADMIN
  • 訪問URL http://localhost:8080/env 後,就看到須要輸入用戶名和密碼了。 
 
緣由分析:
 
  • Actuator endpoints 【斷點】:
 
  
  1. Actuator endpoints allow you to monitor and interact with your application.
  2. Spring Boot includes a number of built-in endpoints and you can also add your own. 
  3. For example the health endpoint provides basic application health information.
  4. Actuator 端點容許您監視和與您的應用程序進行交互。
  5. Spring Boot包含許多內置的端點,您也能夠添加本身的端點。
  6. 例如, health端點提供基本的應用程序健康信息。
  7. The way that endpoints are exposed will depend on the type of technology that you choose.
  8. Most applications choose HTTP monitoring, where the ID of the endpoint is mapped to a URL. 
  9. For example, by default, the health endpoint will be mapped to /health.
  10. 端點的暴露方式取決於您選擇的技術類型。
  11. 大多數應用程序選擇HTTP監視,其中端點的ID映射到一個URL
  12. 例如,默認狀況下,health端點將被映射到/health
 

The following technology agnostic endpoints are available:

ID Description Sensitive
 Default

actuator

Provides a hypermedia-based 「discovery page」 for the other endpoints. Requires Spring HATEOAS to be on the classpath.

爲其餘端點提供基於超媒體的「發現頁面」。要求Spring HATEOAS在類路徑上。

true

auditevents

Exposes audit events information for the current application.

公開當前應用程序的審計事件信息。

true

autoconfig

Displays an auto-configuration report showing all auto-configuration candidates and the reason why they ‘were’ or ‘were not’ applied.

顯示一個auto-configuration的報告,該報告展現全部auto-configuration候選者及它們被應用或未被應用的緣由

true

beans

Displays a complete list of all the Spring beans in your application.

顯示一個應用中全部Spring Beans的完整列表

true

configprops

Displays a collated list of all @ConfigurationProperties.

顯示一個全部@ConfigurationProperties的整理列表

true

dump

Performs a thread dump.

執行一個線程轉儲

true

env

Exposes properties from Spring’s ConfigurableEnvironment.

暴露來自Spring ConfigurableEnvironment的屬性

true

flyway

Shows any Flyway database migrations that have been applied.

顯示已應用的全部Flyway數據庫遷移。

true

health

Shows application health information (when the application is secure, a simple ‘status’ when accessed over an unauthenticated connection or full message details when authenticated).

顯示應用程序運行情況信息(應用程序安全時,經過未經身份驗證的鏈接訪問時的簡單'狀態'或經過身份驗證時的完整郵件詳細信息)。

false

info

Displays arbitrary application info.

顯示任意的應用信息。

false

loggers

Shows and modifies the configuration of loggers in the application.

顯示和修改應用程序中的記錄器配置。

true

liquibase

Shows any Liquibase database migrations that have been applied.

顯示已經應用的任何Liquibase數據庫遷移。

true

metrics

Shows ‘metrics’ information for the current application.

顯示當前應用程序的「指標」信息。

true

mappings

Displays a collated list of all @RequestMapping paths.

顯示全部@RequestMapping路徑的整理列表。

true

shutdown

Allows the application to be gracefully shutdown (not enabled by default).

容許應用程序正常關機(默認狀況下不啓用)。

true

trace

Displays trace information (by default the last 100 HTTP requests).

顯示跟蹤信息(默認最後100個HTTP請求)。

true

 
  • Accessing sensitive endpoints【訪問敏感端點】
 

By default all sensitive HTTP endpoints are secured such that only users that have an ACTUATOR role may access them. 

Security is enforced using the standard HttpServletRequest.isUserInRole method.

(默認狀況下,全部敏感的HTTP端點都是安全的,只有具備ACTUATOR角色的用戶 能夠訪問它們。

安全性是使用標準HttpServletRequest.isUserInRole方法強制執行的 。)

 
   
  1. Use the management.security.roles property if you want something different to ACTUATOR.

If you are deploying applications behind a firewall, you may prefer that all your actuator endpoints can be accessed without requiring authentication. 

You can do this by changing the management.security.enabled property:

application.properties. 

management.security.enabled=false

 

 
   
  1. By default, actuator endpoints are exposed on the same port that serves regular HTTP traffic. 
  2. Take care not to accidentally expose sensitive information if you change the management.security.enabled property.
  3. (默認狀況下,執行器端點暴露在提供常規HTTP通訊的相同端口上。
  4. 注意不要在更改management.security.enabled屬性時意外暴露敏感信息。)

If you’re deploying applications publicly, you may want to add ‘Spring Security’ to handle user authentication. 

When ‘Spring Security’ is added, by default ‘basic’ authentication will be used with the username user and a generated password (which is printed on the console when the application starts).

(若是您公開部署應用程序,則可能須要添加「Spring Security」來處理用戶身份驗證。

當添加「Spring Security」時,默認狀況下,「基本」身份驗證將與用戶名user和生成的密碼一塊兒使用(在應用程序啓動時在控制檯上打印)。)

 
   
  1. Generated passwords are logged as the application starts. Search for Using default security password’.
  2. 生成的密碼在應用程序啓動時被記錄。搜索「使用默認安全密碼」。

You can use Spring properties to change the username and password and to change the security role(s) required to access the endpoints. 

For example, you might set the following in your application.properties:

security.user.name=admin
security.user.password=secret management.security.roles=SUPERUSER

If your application has custom security configuration and you want all your actuator endpoints to be accessible without authentication, you need to explicitly configure that in your security configuration. Along with that, you need to change the management.security.enabledproperty to false.

(若是您的應用程序具備自定義安全配置,而且您但願全部執行器端點無需身份驗證便可訪問,則須要在安全配置中明確配置該端點。與此同時,你須要改變management.security.enabled 屬性false。)

If your custom security configuration secures your actuator endpoints, you also need to ensure that the authenticated user has the roles specified under management.security.roles.

(若是您的自定義安全配置保護您的執行器端點,則還須要確保通過身份驗證的用戶具備在下指定的角色management.security.roles。)

 
   
  1. If you dont have a use case for exposing basic health information to unauthenticated users, 
  2. and you have secured the actuator endpoints with custom security, you can set management.security.enabled to false. 
  3. This will inform Spring Boot to skip the additional role check.
  4. (若是您沒有用於向未經驗證的用戶公開基本健康信息的用例,而且已經使用自定義安全保護了執行器端點,則能夠設置management.security.enabled 爲false。這將通知Spring Boot跳過額外的角色檢查。)
相關文章
相關標籤/搜索