SpringBoot 監控、項目部署

SpringBoot 監控

概述

SpringBoot 自帶監控功能 Actuator,可以幫助實現對程式內部運行情況監控,比如監控狀況、Bean 載入情況、配置屬性、日誌資訊等。

使用

使用步驟

  1. 導入依賴坐標:
    image
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
  1. 訪問 //localhost:8080/acruator
    image
    image

  2. 路徑詳解:

路徑 描述
/beans 描述應用程式上下文里全部的 Bean,以及它們的關係
/env 獲取全部環境屬性
/env/{name} 根據名稱獲取特定的環境屬性值
/health 報告應用程式的健康指標,這些值由 HealthIndicator 的實現類提供
/info 獲取應用程式的訂製資訊,這些資訊由 info 打頭的屬性提供
/mappings 描述全部的 URI 路徑,以及它們和控制器(包含 Actuator 端點)的映射關係
/metrics 報告各種應用程式度量資訊,比如記憶體用量和 HTTP 請求計數
/metrics/{name} 報告指定名稱的應用程式度量值
/trace 提供基本的 HTTP 請求跟蹤資訊(時間戳、HTTP 頭等)
  1. 添加基礎監控資訊:
# 添加 info 資訊
info.name=zhangsan
info.age=23

# 開啟健康檢查的完整資訊
management.endpoint.health.show-details=always

image

image

  1. 添加完整監控資訊:
# 將所有的監控 endpoint 暴露出來
management.endpoints.web.exposure.include=*

如下定義的 RequestMapping,就可通過 /mappings 進行在線監控:

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String sayHello() {
        return "Hello Hello SpringBoot!";
    }
}

image

同時,IDEA 也提供了 Actuator 的查看功能:

image

SpringBoot Admin

概述

  • SpringBoot Admin 是一個開源社區項目,用於管理和監控 SpringBoot 應用程式。
  • SpringBoot Admin 有兩個角色:客戶端(Client)和服務端(Server)。
  • 應用程式作為 SpringBoot Admin Client 向為 Spring Boot Admin Server 註冊。
  • SpringBoot Admin Server 的 UI 介面包含了 SpringBoot Admin Client 的 Actuator Endpoint 上的一些監控資訊。

使用

admin-server

  1. 創建 admin-server 模組
  2. 導入依賴坐標 admin-starter-server
    image
    image
  3. 在引導類上啟用監控功能 @EnableAdminServer

admin-client

  1. 創建 admin-client 模組
  2. 導入依賴坐標 admin-starter-client
  3. 配置相關資訊:server 地址等
  4. 啟動 server 和 client 服務,訪問 server

image

image

SpringBoot 項目部署

SpringBoot 項目開發完畢後,支援兩種方式部署到伺服器:

方式一:jar 包(官方推薦)

  1. 將項目打成 jar 包。
  2. 使用 java -jar 命令啟動內置 Tomcat 進行部署。

方式二:war 包

  1. 將項目改成 war
  2. 啟動類進行以下修改:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

// 繼承 SpringBootServletInitializer
@SpringBootApplication
public class SpringbootDeployApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootDeployApplication.class, args);
    }

    // 重寫以下方法
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(SpringbootDeployApplication.class);
    }
}
  1. 部署到外置 Tomcat 即可。