Spring Boot 揭秘與實戰(九) 應用監控篇 - 自定義監控端點


文章目錄

  1. 1. 繼承 AbstractEndpoint 抽象類
  2. 2. 創建端點配置類
  3. 3. 運行
  4. 4. 源代碼

Spring Boot 提供的端點不能滿足我們的業務需求時,我們可以自定義一個端點。

本文,我將演示一個簡單的自定義端點,用來查看服務器的當前時間,它將返回兩個參數,一個是標准的包含時區的當前時間格式,一個是當前時間的時間戳格式。

繼承 AbstractEndpoint 抽象類

首先,我們需要繼承 AbstractEndpoint 抽象類。因為它是 Endpoint 接口的抽象實現,此外,我們還需要重寫 invoke 方法。

值得注意的是,通過設置 @ConfigurationProperties(prefix = “endpoints.servertime”),我們就可以在 application.properties 中通過 endpoints.servertime 配置我們的端點。

  1. @ConfigurationProperties(prefix="endpoints.servertime")
  2. public class ServerTimeEndpoint extends AbstractEndpoint<Map<String, Object>> {
  3.  
  4. public ServerTimeEndpoint() {
  5. super("servertime", false);
  6. }
  7.  
  8. @Override
  9. public Map<String, Object> invoke() {
  10. Map<String, Object> result = new HashMap<String, Object>();
  11. DateTime dateTime = DateTime.now();
  12. result.put("server_time", dateTime.toString());
  13. result.put("ms_format", dateTime.getMillis());
  14. return result;
  15. }
  16. }

上面的代碼,我解釋下,兩個重要的細節。

  • 構造方法 ServerTimeEndpoint,兩個參數分別表示端點 ID 和是否端點默認是敏感的。我這邊設置端點 ID 是 servertime,它默認不是敏感的。
  • 我們需要通過重寫 invoke 方法,返回我們要監控的內容。這里我定義了一個 Map,它將返回兩個參數,一個是標准的包含時區的當前時間格式,一個是當前時間的時間戳格式。

創建端點配置類

創建端點配置類,並注冊我們的端點 ServerTimeEndpoint。

  1. @Configuration
  2. public class EndpointConfig {
  3. @Bean
  4. public static Endpoint<Map<String, Object>> servertime() {
  5. return new ServerTimeEndpoint();
  6. }
  7. }

運行

啟動應用

  1. @RestController
  2. @EnableAutoConfiguration
  3. @ComponentScan(basePackages = { "com.lianggzone.springboot" })
  4. public class RestfulApiWebDemo {
  5.  
  6. @RequestMapping("/home")
  7. String home() {
  8. return "Hello World!";
  9. }
  10.  
  11. public static void main(String[] args) throws Exception {
  12. SpringApplication.run(RestfulApiWebDemo.class, args);
  13. }
  14. }

訪問 http://localhost:8080/servertime ,此時,你會服務器的當前時間。

  1. {
  2. "ms_format": 1484271566958,
  3. "server_time": "2017-01-13T09:39:26.958+08:00"
  4. }

源代碼

相關示例完整代碼: springboot-action

(完)

 

微信公眾號


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM