成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

超贊!Spring Boot 3.3 自帶 Controller 接口監(jiān)控,大家趕緊用起來(lái)

開發(fā) 前端
Spring Boot 3.3 的 Actuator 模塊為開發(fā)者提供了一整套強(qiáng)大的監(jiān)控功能,使得應(yīng)用程序的健康狀況、性能指標(biāo)、用戶行為及安全性得以全方位掌握和管理。本文將詳細(xì)介紹如何配置和使用 Actuator,并展示如何將這些監(jiān)控?cái)?shù)據(jù)在前端頁(yè)面中可視化。

在現(xiàn)代應(yīng)用開發(fā)中,系統(tǒng)的實(shí)時(shí)監(jiān)控和維護(hù)變得至關(guān)重要。Spring Boot 3.3 的 Actuator 模塊為開發(fā)者提供了一整套強(qiáng)大的監(jiān)控功能,使得應(yīng)用程序的健康狀況、性能指標(biāo)、用戶行為及安全性得以全方位掌握和管理。本文將詳細(xì)介紹如何配置和使用 Actuator,并展示如何將這些監(jiān)控?cái)?shù)據(jù)在前端頁(yè)面中可視化。

Spring Boot 3.3 的 Actuator 模塊提供了一整套全面的監(jiān)控功能,幫助開發(fā)者更好地管理和維護(hù)應(yīng)用程序。主要功能包括:

  1. 健康檢查:實(shí)時(shí)監(jiān)控應(yīng)用的健康狀態(tài),快速發(fā)現(xiàn)和處理系統(tǒng)問(wèn)題,確保應(yīng)用穩(wěn)定運(yùn)行。
  2. 性能指標(biāo):監(jiān)控應(yīng)用的性能數(shù)據(jù),如請(qǐng)求處理時(shí)間和響應(yīng)時(shí)間,幫助識(shí)別和解決性能瓶頸。
  3. 環(huán)境屬性:展示應(yīng)用的環(huán)境配置信息,為調(diào)試和環(huán)境管理提供支持。
  4. 請(qǐng)求追蹤:記錄和分析 HTTP 請(qǐng)求的詳細(xì)信息,幫助追蹤和定位問(wèn)題源頭。
  5. 日志管理:動(dòng)態(tài)調(diào)整日志級(jí)別,方便進(jìn)行問(wèn)題排查和監(jiān)控。
  6. 線程轉(zhuǎn)儲(chǔ):提供 JVM 線程的詳細(xì)轉(zhuǎn)儲(chǔ)信息,幫助分析線程狀態(tài)和優(yōu)化性能。

這些功能使得開發(fā)者能夠?qū)崟r(shí)獲取應(yīng)用的運(yùn)行狀態(tài),優(yōu)化系統(tǒng)性能,提升用戶體驗(yàn),并增強(qiáng)系統(tǒng)的安全性。接下來(lái),我們將展示如何配置 Actuator 及其功能,并如何在前端頁(yè)面中展示這些監(jiān)控?cái)?shù)據(jù)。

運(yùn)行效果:

圖片圖片

若想獲取項(xiàng)目完整代碼以及其他文章的項(xiàng)目源碼,且在代碼編寫時(shí)遇到問(wèn)題需要咨詢交流,歡迎加入下方的知識(shí)星球。

項(xiàng)目依賴配置

首先,確保你的 pom.xml 文件中包含 Actuator 和 Thymeleaf 的依賴。

<?xml versinotallow="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>3.3.3</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.icoderoad</groupId>
	<artifactId>actuator-demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>actuator-demo</name>
	<description>Demo project for Spring Boot</description>
	
	<properties>
		<java.version>17</java.version>
	</properties>
	<dependencies>
		
		<!-- Spring Boot Starter Web -->
	    <dependency>
	        <groupId>org.springframework.boot</groupId>
	        <artifactId>spring-boot-starter-web</artifactId>
	    </dependency>
	    
	    <!-- Spring Boot Actuator -->
	    <dependency>
	        <groupId>org.springframework.boot</groupId>
	        <artifactId>spring-boot-starter-actuator</artifactId>
	    </dependency>
	
	    <!-- Thymeleaf for HTML templates -->
	    <dependency>
	        <groupId>org.springframework.boot</groupId>
	        <artifactId>spring-boot-starter-thymeleaf</artifactId>
	    </dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

配置 Actuator 監(jiān)控功能

在 application.yml 中配置 Actuator 端點(diǎn),啟用所需的監(jiān)控功能。

server:
  port: 8080
    
management:
  endpoints:
    web:
      exposure:
        include: health, metrics, info, mappings, env, conditions, loggers, threaddump
  endpoint:
    health:
      show-details: always
    metrics:
      enable:
        all: true
    info:
      enabled: true
    mappings:
      enabled: true
    env:
      enabled: true
    conditions:
      enabled: true
    loggers:
      enabled: true
    threaddump:
      enabled: true
  trace:
    http:
      enabled: true

創(chuàng)建 Actuator 監(jiān)控 Controller

創(chuàng)建一個(gè) MonitoringController,用于展示 Actuator 的監(jiān)控?cái)?shù)據(jù)。

package com.icoderoad.actuator_demo.controller;

import org.springframework.boot.actuate.env.EnvironmentEndpoint;
import org.springframework.boot.actuate.health.HealthEndpoint;
import org.springframework.boot.actuate.info.InfoEndpoint;
import org.springframework.boot.actuate.logging.LoggersEndpoint;
import org.springframework.boot.actuate.management.ThreadDumpEndpoint;
import org.springframework.boot.actuate.metrics.MetricsEndpoint;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/monitoring")
public class MonitoringController {

    private final HealthEndpoint healthEndpoint;
    private final MetricsEndpoint metricsEndpoint;
    private final InfoEndpoint infoEndpoint;
    private final EnvironmentEndpoint environmentEndpoint;
    private final LoggersEndpoint loggersEndpoint;
    private final ThreadDumpEndpoint threadDumpEndpoint;

    public MonitoringController(HealthEndpoint healthEndpoint, MetricsEndpoint metricsEndpoint,
                                InfoEndpoint infoEndpoint, EnvironmentEndpoint environmentEndpoint,
                                LoggersEndpoint loggersEndpoint, ThreadDumpEndpoint threadDumpEndpoint) {
        this.healthEndpoint = healthEndpoint;
        this.metricsEndpoint = metricsEndpoint;
        this.infoEndpoint = infoEndpoint;
        this.environmentEndpoint = environmentEndpoint;
        this.loggersEndpoint = loggersEndpoint;
        this.threadDumpEndpoint = threadDumpEndpoint;
    }

    @GetMapping
    public Map<String, Object> getMonitoringData() {
        Map<String, Object> monitoringData = new HashMap<>();
        
        monitoringData.put("health", healthEndpoint.health());
        monitoringData.put("metrics", metricsEndpoint.listNames());
        monitoringData.put("info", infoEndpoint.info());
        monitoringData.put("environment", environmentEndpoint.environment(null)); // 返回環(huán)境屬性描述符
        monitoringData.put("loggers", loggersEndpoint.loggers());
        monitoringData.put("threaddump", threadDumpEndpoint.threadDump());

        return monitoringData;
    }
}

創(chuàng)建用戶菜單接口

創(chuàng)建一個(gè)新的接口 /menu,用于提供用戶菜單數(shù)據(jù)。

package com.icoderoad.actuator_demo.controller;

import java.util.List;
import java.util.Map;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class UserController {

    @GetMapping("/menu")
    public List<Map<String, String>> getMenu() {
        // 模擬返回用戶菜單
        return List.of(
            Map.of("name", "首頁(yè)", "url", "/home"),
            Map.of("name", "用戶管理", "url", "/users"),
            Map.of("name", "設(shè)置", "url", "/settings")
        );
    }
}

視圖控制器

package com.icoderoad.actuator_demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class IndexController {

    @GetMapping("/")
    public String index() {
        return "index";
    }
}

創(chuàng)建 Thymeleaf 模板

在 src/main/resources/templates 目錄下創(chuàng)建或更新 monitoring.html 文件,以展示 Actuator 監(jiān)控?cái)?shù)據(jù)和測(cè)試接口結(jié)果。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>接口監(jiān)控</title>
    <link rel="stylesheet" >
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
    	.container {
    		width: 40%;
    		margin: 40px auto;
    	}
        pre {
            white-space: pre-wrap; /* Allow text to wrap within the element */
            word-wrap: break-word; /* Break long words */
        }
    </style>
</head>
<body>
    <div class="container mt-5">
        <h1>接口監(jiān)控</h1>
        
        <!-- 接口健康狀態(tài) -->
        <div class="mt-3">
            <h3>接口健康狀態(tài)</h3>
            <button class="btn btn-info" onclick="toggleContent('health', fetchHealth)">顯示健康狀態(tài)</button>
            <pre id="health" style="display: none;"></pre>
        </div>
        
        <!-- 可用指標(biāo) -->
        <div class="mt-3">
            <h3>可用指標(biāo)</h3>
            <button class="btn btn-info" onclick="toggleContent('metrics', fetchMetrics)">顯示可用指標(biāo)</button>
            <pre id="metrics" style="display: none;"></pre>
        </div>
        
        <!-- 環(huán)境屬性 -->
        <div class="mt-3">
            <h3>環(huán)境屬性</h3>
            <button class="btn btn-info" onclick="toggleContent('environment', fetchEnvironment)">顯示環(huán)境屬性</button>
            <pre id="environment" style="display: none;"></pre>
        </div>
        
        <!-- 日志級(jí)別 -->
        <div class="mt-3">
            <h3>日志級(jí)別</h3>
            <button class="btn btn-info" onclick="toggleContent('loggers', fetchLoggers)">顯示日志級(jí)別</button>
            <pre id="loggers" style="display: none;"></pre>
        </div>
        
        <!-- 線程轉(zhuǎn)儲(chǔ) -->
        <div class="mt-3">
            <h3>線程轉(zhuǎn)儲(chǔ)</h3>
            <button class="btn btn-info" onclick="toggleContent('threaddump', fetchThreadDump)">顯示線程轉(zhuǎn)儲(chǔ)</button>
            <pre id="threaddump" style="display: none;"></pre>
        </div>

        <!-- 用戶菜單 -->
        <div class="mt-3">
            <h3>用戶菜單</h3>
            <a href="#" class="btn btn-primary" onclick="fetchUserMenu()">訪問(wèn)用戶菜單接口</a>
            <div id="menu-result" class="mt-2"></div>
        </div>
    </div>

    <script>
        function fetchMonitoringData() {
            fetch('/monitoring')
                .then(response => response.json())
                .then(data => {
                    // Store the data in the global scope for later use
                    window.monitoringData = data;
                })
                .catch(error => console.error('Error fetching monitoring data:', error));
        }

        function fetchHealth() {
            if (!window.monitoringData) {
                fetchMonitoringData();
                return;
            }
            return JSON.stringify(window.monitoringData.health, null, 2);
        }

        function fetchMetrics() {
            if (!window.monitoringData) {
                fetchMonitoringData();
                return;
            }
            return JSON.stringify(window.monitoringData.metrics, null, 2);
        }

        function fetchEnvironment() {
            if (!window.monitoringData) {
                fetchMonitoringData();
                return;
            }
            return JSON.stringify(window.monitoringData.environment, null, 2);
        }

        function fetchLoggers() {
            if (!window.monitoringData) {
                fetchMonitoringData();
                return;
            }
            return JSON.stringify(window.monitoringData.loggers, null, 2);
        }

        function fetchThreadDump() {
            if (!window.monitoringData) {
                fetchMonitoringData();
                return;
            }
            return JSON.stringify(window.monitoringData.threaddump, null, 2);
        }

        function fetchUserMenu() {
            fetch('/api/menu')
                .then(response => response.json())
                .then(data => {
                    document.getElementById('menu-result').textContent = JSON.stringify(data, null, 2);
                })
                .catch(error => console.error('Error fetching user menu:', error));
        }

        function toggleContent(id, fetchFunction) {
            const content = document.getElementById(id);
            const button = event.target;
            
            if (content.style.display === 'none') {
                // Display content
                content.textContent = fetchFunction();
                content.style.display = 'block';
                button.textContent = `隱藏${button.textContent.substring(2)}`;
            } else {
                // Hide content
                content.style.display = 'none';
                button.textContent = `顯示${button.textContent.substring(2)}`;
            }
        }

        // Trigger fetchMonitoringData on page load
        window.onload = function() {
            fetchMonitoringData();
        }
    </script>
</body>
</html>

運(yùn)行并測(cè)試

  1. 啟動(dòng) Spring Boot 應(yīng)用程序。
  2. 訪問(wèn) http://localhost:8080 頁(yè)面,查看 Actuator 提供的監(jiān)控?cái)?shù)據(jù)。
  3. 點(diǎn)擊“訪問(wèn)用戶菜單接口”按鈕,查看用戶菜單接口的響應(yīng)數(shù)據(jù)。

通過(guò)以上步驟,你可以輕松驗(yàn)證 Actuator 的 HTTP 請(qǐng)求追蹤功能,并在頁(yè)面上測(cè)試用戶菜單接口。這樣不僅能夠展示 Actuator 的強(qiáng)大功能,還可以檢查和調(diào)試接口的響應(yīng)數(shù)據(jù)。這篇文章希望能幫助大家有效地實(shí)現(xiàn)和利用 Spring Boot 的監(jiān)控功能,并提升系統(tǒng)的管理和維護(hù)能力。

責(zé)任編輯:武曉燕 來(lái)源: 路條編程
相關(guān)推薦

2024-07-04 11:33:33

2021-01-29 17:40:00

Flyme安卓手機(jī)安全

2024-09-13 10:21:50

2021-06-30 09:20:18

NuShell工具Linux

2020-08-25 08:00:18

Python開發(fā)數(shù)據(jù)庫(kù)

2024-08-12 12:20:49

Controller接口性能

2024-10-08 09:27:04

SpringRESTfulAPI

2021-03-10 09:54:43

RustNuShell系統(tǒng)

2019-08-08 16:12:33

2017-09-12 16:25:17

Spring Clou中小型公司Spring Boot

2012-07-11 09:34:39

微軟云計(jì)算

2022-05-22 21:16:46

TypeScriptOmit 工具

2024-10-11 11:46:40

2022-05-18 08:32:05

服務(wù)監(jiān)控Prometheus開源

2024-10-30 08:05:01

Spring參數(shù)電子簽章

2025-01-08 09:35:55

Spring性能監(jiān)控

2025-04-08 01:00:00

Spring開發(fā)系統(tǒng)

2021-09-18 08:52:45

人工智能

2024-10-18 11:32:15

2024-05-21 10:28:51

API設(shè)計(jì)架構(gòu)
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)

主站蜘蛛池模板: 精品视频在线免费观看 | 一区在线免费视频 | 精品九九在线 | 亚洲草草视频 | 日本福利片 | 免费网站国产 | 欧美成人猛片aaaaaaa | 精品入口麻豆88视频 | 国产成人精品999在线观看 | 亚洲精品一区二区三区丝袜 | 日本一区二区高清不卡 | 日本三级做a全过程在线观看 | 欧美日韩高清在线一区 | 色黄网站 | 一色桃子av一区二区 | 免费黄色a视频 | 免费在线观看成年人视频 | 精品乱码一区二区三四区视频 | 国产激情一区二区三区 | 狠狠av| 亚洲免费视频网站 | 免费的日批视频 | 国产成人精品在线播放 | 国产黄色小视频 | 国产视频一区在线 | 亚洲精品久久久久久久久久久 | 97成人在线 | 国产精品美女久久久 | 999精品视频 | 日本成人综合 | 成人一区二区视频 | 99在线资源 | 色婷婷一区二区三区四区 | 男人的天堂在线视频 | 久久久久国产 | 中文二区| 国产精品久久久久久久久久久久久久 | 九九免费视频 | 91久久久久 | 欧美日韩不卡在线 | 日韩a在线 |