日韩成人免费在线_国产成人一二_精品国产免费人成电影在线观..._日本一区二区三区久久久久久久久不

當(dāng)前位置:首頁 > 科技  > 軟件

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

來源: 責(zé)編: 時(shí)間:2024-09-10 09:50:59 116觀看
導(dǎo)讀在現(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ì)介

在現(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ù)在前端頁面中可視化。OPt28資訊網(wǎng)——每日最新資訊28at.com

Spring Boot 3.3 的 Actuator 模塊提供了一整套全面的監(jiān)控功能,幫助開發(fā)者更好地管理和維護(hù)應(yīng)用程序。主要功能包括:OPt28資訊網(wǎng)——每日最新資訊28at.com

  1. 健康檢查:實(shí)時(shí)監(jiān)控應(yīng)用的健康狀態(tài),快速發(fā)現(xiàn)和處理系統(tǒng)問題,確保應(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ì)信息,幫助追蹤和定位問題源頭。
  5. 日志管理:動(dòng)態(tài)調(diào)整日志級(jí)別,方便進(jì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)的安全性。接下來,我們將展示如何配置 Actuator 及其功能,并如何在前端頁面中展示這些監(jiān)控?cái)?shù)據(jù)。OPt28資訊網(wǎng)——每日最新資訊28at.com

運(yùn)行效果:OPt28資訊網(wǎng)——每日最新資訊28at.com

圖片圖片OPt28資訊網(wǎng)——每日最新資訊28at.com

若想獲取項(xiàng)目完整代碼以及其他文章的項(xiàng)目源碼,且在代碼編寫時(shí)遇到問題需要咨詢交流,歡迎加入下方的知識(shí)星球。OPt28資訊網(wǎng)——每日最新資訊28at.com

項(xiàng)目依賴配置

首先,確保你的 pom.xml 文件中包含 Actuator 和 Thymeleaf 的依賴。OPt28資訊網(wǎng)——每日最新資訊28at.com

<?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)控功能。OPt28資訊網(wǎng)——每日最新資訊28at.com

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ù)。OPt28資訊網(wǎng)——每日最新資訊28at.com

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ù)。OPt28資訊網(wǎng)——每日最新資訊28at.com

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", "首頁", "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;@Controllerpublic 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é)果。OPt28資訊網(wǎng)——每日最新資訊28at.com

<!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()">訪問用戶菜單接口</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. 訪問 http://localhost:8080 頁面,查看 Actuator 提供的監(jiān)控?cái)?shù)據(jù)。
  3. 點(diǎn)擊“訪問用戶菜單接口”按鈕,查看用戶菜單接口的響應(yīng)數(shù)據(jù)。

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

本文鏈接:http://www.www897cc.com/showinfo-26-112780-0.html超贊!Spring Boot 3.3 自帶 Controller 接口監(jiān)控,大家趕緊用起來

聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。郵件:2376512515@qq.com

上一篇: PHP異步非阻塞MySQL客戶端連接池

下一篇: 如何使用 CGLIB 在 Spring Boot 3.3 中實(shí)現(xiàn)動(dòng)態(tài)代理

標(biāo)簽:
  • 熱門焦點(diǎn)
  • K60 Pro官方停產(chǎn) 第三方瞬間漲價(jià)

    雖然沒有官方宣布,但Redmi的一些高管也已經(jīng)透露了,Redmi K60 Pro已經(jīng)停產(chǎn)且不會(huì)補(bǔ)貨,這一切都是為了即將到來的K60 Ultra鋪路,屬于廠家的正常操作。但有意思的是該機(jī)在停產(chǎn)之后
  • 28個(gè)SpringBoot項(xiàng)目中常用注解,日常開發(fā)、求職面試不再懵圈

    前言在使用SpringBoot開發(fā)中或者在求職面試中都會(huì)使用到很多注解或者問到注解相關(guān)的知識(shí)。本文主要對(duì)一些常用的注解進(jìn)行了總結(jié),同時(shí)也會(huì)舉出具體例子,供大家學(xué)習(xí)和參考。注解
  • 分布式系統(tǒng)中的CAP理論,面試必問,你理解了嘛?

    對(duì)于剛剛接觸分布式系統(tǒng)的小伙伴們來說,一提起分布式系統(tǒng),就感覺高大上,深不可測(cè)。而且看了很多書和視頻還是一臉懵逼。這篇文章主要使用大白話的方式,帶你理解一下分布式系統(tǒng)
  • 之家push系統(tǒng)迭代之路

    前言在這個(gè)信息爆炸的互聯(lián)網(wǎng)時(shí)代,能夠及時(shí)準(zhǔn)確獲取信息是當(dāng)今社會(huì)要解決的關(guān)鍵問題之一。隨著之家用戶體量和內(nèi)容規(guī)模的不斷增大,傳統(tǒng)的靠"主動(dòng)拉"獲取信息的方式已不能滿足用
  • 2天漲粉255萬,又一賽道在抖音爆火

    來源:運(yùn)營(yíng)研究社作者 | 張知白編輯 | 楊佩汶設(shè)計(jì) | 晏談夢(mèng)潔這個(gè)暑期,旅游賽道徹底火了:有的「地方」火了&mdash;&mdash;貴州村超旅游收入 1 個(gè)月超過 12 億;有的「博主」火了&m
  • 阿里瓴羊One推出背后,零售企業(yè)迎數(shù)字化新解

    作者:劉曠近年來隨著數(shù)字經(jīng)濟(jì)的高速發(fā)展,各式各樣的SaaS應(yīng)用服務(wù)更是層出不窮,但本質(zhì)上SaaS大多局限于單一業(yè)務(wù)流層面,對(duì)用戶核心關(guān)切的增長(zhǎng)問題等則沒有提供更好的解法。在Saa
  • AMD的AI芯片轉(zhuǎn)單給三星可能性不大 與臺(tái)積電已合作至2nm制程

    據(jù) DIGITIMES 消息,英偉達(dá) AI GPU 出貨逐季飆升,接下來 AMD MI 300 系列將在第 4 季底量產(chǎn)。而半導(dǎo)體業(yè)內(nèi)人士表示,近日傳出 AMD 的 AI 芯片將轉(zhuǎn)單給
  • 與兆芯合作 聯(lián)想推出全新旗艦版筆記本電腦開天N7系列

    聯(lián)想與兆芯合作推出全新聯(lián)想旗艦版筆記本電腦開天 N7系列。這個(gè)系列采用兆芯KX-6640MA處理器平臺(tái),KX-6640MA 處理器是采用了陸家嘴架構(gòu),16nm 工藝,4 核 4 線
  • “買真退假” 這種“羊毛”不能薅

    □ 法治日?qǐng)?bào) 記者 王春   □ 本報(bào)通訊員 胡佳麗  2020年初,還在上大學(xué)的小東加入了一個(gè)大學(xué)生兼職QQ群。群主&ldquo;七王&rdquo;在群里介紹一些刷單賺
Top 主站蜘蛛池模板: 偃师市| 闵行区| 邵阳市| 安新县| 三江| 清水河县| 茂名市| 定结县| 大埔县| 黎城县| 行唐县| 浠水县| 葫芦岛市| 海门市| 夹江县| 灵台县| 德安县| 噶尔县| 麻阳| 东丽区| 建德市| 云梦县| 仙桃市| 措勤县| 桂阳县| 遂溪县| 新野县| 平和县| 洛阳市| 阿勒泰市| 海兴县| 沾益县| 湘潭市| 象山县| 江川县| 乌鲁木齐市| 平山县| 齐齐哈尔市| 黄骅市| 仁化县| 阿城市|