当前位置: 首页 > news >正文

Spring Cloud微服务Actuator和Vue

目录

  • 前言
  • 一、引入Actuator依赖
  • 二、暴露Actuator端点
      • 1. 配置文件
      • 2. 监控端点
  • 三、自定义健康检查
      • 自定义健康检查类
  • 四、vue前端代码
  • 五、监控器的优势
  • 六、监控指标的可视化
      • 1. Grafana
      • 2. Prometheus
  • 七、安全性考虑
      • 安全配置示例
  • 八、总结

前言

随着微服务架构的流行,对系统运行状况的监控和管理变得至关重要。Spring Cloud提供了强大的监控工具Actuator,能够实时监控服务的运行状态、性能指标和健康状况。本文将介绍如何使用Spring Cloud的Actuator来实现微服务的监控。


一、引入Actuator依赖

首先,我们需要在项目中引入Spring Boot Actuator的依赖。

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

这样做会自动添加Actuator相关的端点,我们可以通过这些端点来获取系统的运行信息。


二、暴露Actuator端点

默认情况下,Actuator的端点是不对外暴露的,为了方便监控,我们需要手动配置来暴露这些端点。

1. 配置文件

yamlCopy codemanagement:endpoints:web:exposure:include: "*" # 暴露所有端点base-path: /monitor # 设置端点的根路径endpoint:health:show-details: always # 显示健康检查的详细信息shutdown:enabled: true # 启用关闭应用的端点

在上述配置中,我们通过 management.endpoints.web.exposure.include 指定了要暴露的端点,这里设置为 * 表示暴露所有端点。同时,我们将端点的根路径设置为 /monitor,方便统一管理。

2. 监控端点

Spring Boot Actuator提供了许多端点,包括 /health/info/metrics 等。这些端点可以提供关于应用程序运行状况的信息。

例如,访问 /monitor/health 端点可以获取应用程序的健康状况信息。


三、自定义健康检查

有时候,我们需要根据业务需求自定义健康检查逻辑。Spring Boot Actuator允许我们通过实现 HealthIndicator 接口来自定义健康检查。

自定义健康检查类

package cn.weizi.main.endpoint;import cn.weizi.main.pojo.R;
import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.concurrent.atomic.AtomicLong;@Service
@CrossOrigin
@RestController
@RequestMapping("/Custom")
public class CustomHealthIndicator extends AbstractHealthIndicator {private final AtomicLong lastRequestTime = new AtomicLong(System.currentTimeMillis());@Overrideprotected void doHealthCheck(Health.Builder builder) {long currentTime = System.currentTimeMillis();long timeSinceLastRequest = currentTime - lastRequestTime.get();try {if (timeSinceLastRequest <= 10000) {builder.up();} else {builder.down().withDetail("error", "10秒内没有请求");}} catch (Exception ex) {builder.down().withException(ex);}}@GetMapping("check")private R check() {// 处理实际的请求逻辑lastRequestTime.set(System.currentTimeMillis());// 这里可以放置其他处理逻辑return new R(true, "UP");}
}

在上述示例中,我们实现了一个自定义的健康检查类 CustomHealthIndicator,通过继承 AbstractHealthIndicator 并实现 doHealthCheck 方法来自定义健康检查逻辑。在这里,我们检查了最后一次请求的时间,如果超过10秒没有请求,将会返回一个健康状态为 DOWN 的信息。


四、vue前端代码

<template><div><van-notice-bar left-icon="volume-o" text="为了减少系统占用,此页面每5秒刷新一次,如果不想等待,可以下拉刷新"/><div v-if="loadingShow"><van-overlay :show="loadingShow"><div @click.stop><van-loading size="50px">加载中...</van-loading></div></van-overlay></div><div v-else><van-cell-group><van-cellv-for="(component, componentName) in data.components":key="componentName":title="componentName":label="getStatusTag(component.status)":value="component.status === 'DOWN' ? '查看异常' : '运行正常'"@click="handleCellClick(component)"/></van-cell-group><van-dialog v-model="dialogVisible" title="异常" theme="round-button"><p class="error-message">{{ currentComponentError }}</p></van-dialog></div></div>
</template><script>import request from "@/unilts/request";
import redirectToHome from "@/unilts/redirectToHome";export default {components: {},data() {return {dialogVisible: false,currentComponentError: '',loadingShow: false,data: {status: 'UP',components: {EVS: {status: 'UP',details: {error: 'null',},},},},};},created() {this.onDataInit();// 初始加载数据this.timer = setInterval(() => {this.onDataInit(); // 每隔一定时间重新加载数据}, 5000); // 5秒一次,可以根据需求调整时间间隔},destroyed() {clearInterval(this.timer); // 清除定时器,防止内存泄漏},methods: {async onDataInit() {this.loadingShow = true;await request.get("/SystemState/health").then((res) => {console.log(res.data)if (res.data.flag) {this.data = res.data.data;} else {this.data = res.data.data;}}).finally(() => {this.loadingShow = false;})},getStatusTag(status) {if (status === 'UP') {return <van-tag type="success">正常</van-tag>;} else {return <van-tag type="danger">异常</van-tag>;}},handleCellClick(component) {this.currentComponentError = '';if (component.status === 'DOWN') {this.currentComponentError = component.details.error;this.dialogVisible = true;}},},
};
</script>
<style>
.error-message {white-space: pre-line;word-wrap: break-word;max-width: 30ch; /* 可根据需要调整最大宽度 */margin: auto; /* 添加居中的样式 */text-align: center; /* 文本水平居中 */
}
</style>

五、监控器的优势

  1. 实时监控:Actuator提供了丰富的端点,能够实时监控系统的运行状况、性能指标和健康状况,帮助开发人员及时发现并解决问题。
  2. 可配置性:通过配置文件,我们可以灵活地控制哪些端点需要暴露,从而保证系统的安全性和稳定性。
  3. 自定义扩展:Actuator允许开发人员自定义健康检查逻辑,根据具体业务需求进行监控和管理,使得监控更加灵活和定制化。

六、监控指标的可视化

除了通过端点获取监控信息外,我们还可以将监控指标可视化,以便更直观地了解系统的运行状况。常见的可视化工具包括Grafana和Prometheus等。

1. Grafana

Grafana是一款开源的数据可视化工具,支持多种数据源,并提供丰富的图表和仪表盘功能。我们可以通过将Actuator的监控数据导入到Grafana中,实现监控指标的可视化展示。

2. Prometheus

Prometheus是一款开源的监控系统,可以实时收集并存储时间序列数据,支持多维度的查询和告警功能。我们可以将Actuator暴露的监控端点数据导入到Prometheus中,从而实现监控指标的存储和分析。

通过与Grafana或Prometheus等工具的集成,我们可以更直观地了解系统的运行情况,并及时采取措施应对潜在的问题,保证系统的稳定性和可靠性。


七、安全性考虑

在暴露Actuator端点时,我们需要考虑系统的安全性。默认情况下,Actuator的端点是不对外暴露的,我们需要手动配置来暴露这些端点,并且可以通过配置用户名和密码来保护这些端点。

安全配置示例

yamlCopy codespring:security:user:name: adminpassword: password
management:endpoints:web:exposure:include: "*"endpoint:health:show-details: alwaysshutdown:enabled: true

在上述配置中,我们通过 spring.security.user 配置了用户名和密码,用于保护Actuator端点。只有提供了正确的用户名和密码才能访问这些端点,从而确保系统的安全性。


八、总结

本文介绍了如何使用Spring Cloud的Actuator来实现微服务的监控,并介绍了监控指标的可视化、安全性考虑和监控告警机制等相关内容。Actuator作为微服务架构中不可或缺的监控工具,为开发人员提供了实时监控系统运行状况的便利,并帮助他们及时发现并解决问题,保证系统的稳定性和可靠性。

通过合理配置和使用Actuator,我们可以更好地管理和监控微服务,提高系统的可维护性和可靠性,为用户提供更好的服务体验。

在本文中,我们深入探讨了Actuator的配置和使用,以及与其他监控工具的集成,希望能够对读者在微服务监控领域的实践提供一些参考和帮助。 Actuator的强大功能和灵活性为微服务的监控和管理提供了便利,是现代软件开发中不可或缺的重要组件。

相关文章:

  • vite打包配置基础
  • B端设计:如何让UI组件库成为助力,而不是阻力。
  • AcWing 796. 子矩阵的和
  • HTML语言
  • webRtc麦克风摄像头检测
  • mysql基础2多表查询
  • php搭建websocket
  • mybatis实践篇(二)
  • OSPF-1类Router LSA学习
  • 2024 年广西职业院校技能大赛高职组《云计算应用》赛项赛题第 2 套
  • Java设计模式之单例模式(多种实现方式)
  • 手撕算法-删除链表的倒数第 N 个结点
  • 抖音IP属地怎么更改
  • pta-洛希极限
  • PostgreSQL关系型数据库介绍与部署
  • Asm.js的简单介绍
  • React Native移动开发实战-3-实现页面间的数据传递
  • vue和cordova项目整合打包,并实现vue调用android的相机的demo
  • 基于Vue2全家桶的移动端AppDEMO实现
  • 开年巨制!千人千面回放技术让你“看到”Flutter用户侧问题
  • 七牛云 DV OV EV SSL 证书上线,限时折扣低至 6.75 折!
  • 让你成为前端,后端或全栈开发程序员的进阶指南,一门学到老的技术
  • 使用Swoole加速Laravel(正式环境中)
  • 优化 Vue 项目编译文件大小
  • 原生js练习题---第五课
  • 在weex里面使用chart图表
  • 策略 : 一文教你成为人工智能(AI)领域专家
  • 通过调用文摘列表API获取文摘
  • 新海诚画集[秒速5センチメートル:樱花抄·春]
  • $$$$GB2312-80区位编码表$$$$
  • (007)XHTML文档之标题——h1~h6
  • (14)学习笔记:动手深度学习(Pytorch神经网络基础)
  • (TipsTricks)用客户端模板精简JavaScript代码
  • (笔试题)分解质因式
  • (二)斐波那契Fabonacci函数
  • (十六)Flask之蓝图
  • (原)Matlab的svmtrain和svmclassify
  • (原創) 博客園正式支援VHDL語法著色功能 (SOC) (VHDL)
  • (转)为C# Windows服务添加安装程序
  • (转载)OpenStack Hacker养成指南
  • .NET CF命令行调试器MDbg入门(四) Attaching to Processes
  • .NET 设计一套高性能的弱事件机制
  • .NET 中小心嵌套等待的 Task,它可能会耗尽你线程池的现有资源,出现类似死锁的情况
  • .net知识和学习方法系列(二十一)CLR-枚举
  • .Net转前端开发-启航篇,如何定制博客园主题
  • /dev下添加设备节点的方法步骤(通过device_create)
  • [] 与 [[]], -gt 与 > 的比较
  • [100天算法】-实现 strStr()(day 52)
  • [17]JAVAEE-HTTP协议
  • [20180224]expdp query 写法问题.txt
  • [BJDCTF2020]The mystery of ip
  • [CLickhouse] 学习小计
  • [EFI]Dell Inspiron 15 5567 电脑 Hackintosh 黑苹果efi引导文件
  • [GPT]Andrej Karpathy微软Build大会GPT演讲(上)--GPT如何训练
  • [hive] 窗口函数 ROW_NUMBER()