面试题答案
一键面试Spring Boot应用常见监控指标
- 内存使用:包括堆内存、非堆内存的使用情况。堆内存用于存放对象实例,非堆内存用于加载类、常量池等。监控堆内存使用率有助于判断应用是否存在内存泄漏或过度消耗内存的情况。
- CPU占用:反映应用对CPU资源的消耗程度。高CPU占用可能表示应用存在复杂计算、死循环或线程竞争等问题。
- 请求响应时间:衡量从客户端发起请求到接收到响应所花费的时间。过长的响应时间会影响用户体验,可能是由于业务逻辑复杂、数据库查询慢或网络问题等原因导致。
- 线程状态:线程是应用执行的基本单位,监控线程状态(如运行、阻塞、等待等)可以了解应用内部的并发执行情况,排查线程死锁或线程池耗尽等问题。
- 垃圾回收:了解垃圾回收的频率、回收时间以及回收的内存量等信息。频繁的垃圾回收可能暗示对象创建过于频繁或内存分配不合理。
使用Spring Boot Actuator实现监控
- 添加依赖:在
pom.xml
文件中添加Spring Boot Actuator依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
- 配置暴露端点:默认情况下,Actuator仅暴露
health
和info
端点。可以通过配置暴露更多端点,例如在application.properties
文件中:
management.endpoints.web.exposure.include=*
此配置将暴露所有端点,生产环境中可按需配置暴露特定端点。
3. 访问监控指标:启动应用后,可以通过http://localhost:8080/actuator/metrics
访问所有支持的指标列表,例如http://localhost:8080/actuator/metrics/jvm.memory.used
获取JVM内存使用指标。
将监控数据展示到Grafana
- 选择数据收集工具:常用的有Prometheus。首先添加Prometheus依赖到Spring Boot项目:
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
配置Prometheus相关属性,如在application.properties
中:
management.metrics.export.prometheus.enabled=true
management.endpoints.web.base-path=/actuator
- 配置Prometheus:在Prometheus的配置文件
prometheus.yml
中添加Spring Boot应用的监控地址:
scrape_configs:
- job_name:'spring-boot-actuator'
static_configs:
- targets: ['localhost:8080']
metrics_path: /actuator/prometheus
- 配置Grafana:
- 安装并启动Grafana。
- 在Grafana中添加Prometheus数据源,配置Prometheus的访问地址。
- 导入适合Spring Boot监控数据展示的Dashboard模板。可在Grafana官方Dashboard库(https://grafana.com/grafana/dashboards)搜索下载相关模板,导入后即可在Grafana界面直观查看Spring Boot应用的各项监控指标。