0、概述
常见服务性能监控,调研发现,目前使用较多的,有两种方案:
- spring-boot-admin;
- promethus + grafana;
两种方式本质上都是基于 spring-boot-actuator 的方式,而基于 actuator,虽然提供了生产级别的功能,比如健康检查,审计,指标收集,HTTP 跟踪等,帮助我们监控和管理Spring Boot 应用,但是也带来安全问题。
相较于 promethus + grafana,admin 部署、运行较简单,但是数据化可视化方面较差一点,且更加重要一点,使用 prometheus 可将中间件的服务性能一起监控。
1、基础架构
2、修改 Java(Spring)服务
2.1、引入 jar 包
<!-- =================== 引入性能监控 =================== -->
<!-- actuator 配置位于 application.yaml 中的 management 下 -->
<!-- 警惕该组件可能带来的服务安全问题 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
<!-- =================== /引入性能监控 =================== -->
2.2、修改配置
management:
server:
# 不允许远程管理连接,安全性考虑,指定的 ip 必须是部署服务器可以 ping 的通的
address: 192.168.x.xx
# 自定义端口
port: 30000
endpoints:
web:
exposure:
# 允许端点
include: "*"
# 排除端点
exclude: shutdown
# 修改访问前缀,默认为 /actuator
base-path: /testMonitor
endpoint:
# 从 Spring 的 ConfigurableEnvironment 中公开属性,默认开启
env:
enabled: false
# 显示 db、redis 等连接情况等
health:
show-details: always
通过配置项进行避免引入 actuator 带来的安全问题:
- 配置 management.server 下的 address 与 port:
- address 选择局域网内部署 prometheus 的服务器地址;
- port 区别于 server.port;
- 如果多个服务部署在同一台服务器上,各个服务需要指定合适的端口;
- address 选择局域网内部署 prometheus 的服务器地址;
- 通过 base-path 修改默认的访问前缀:/actuator;
- 修改为:/testMonitor;
- 使用账号密码(会引入 spring-security),在 prometheus 配置时,需要同步配置;(建议使用该种方式,本文不演示)
- 隐藏重要信息或关闭危险操作;
2.3、手动注入实例到容器
该 bean 可不注册,但是不注册,在 grafana 处,查看 prometheus 下的 jar 包服务实例时,就会找不到 applicationName。
@Bean
public MeterRegistryCustomizer<MeterRegistry> meterRegistryCustomizer(@Value("${spring.application.name}") String applicationName) {
return (registry) -> registry.config().commonTags("application", applicationName);
}
3、中间件安装
3.1、prometheus
相关文档
github:GitHub - prometheus/prometheus: The Prometheus monitoring system and time series database.
启动命令
无需指定 prometheus 版本,使用最新启动即可,另外启动时,设置容器跟随 docker 生命周期。
docker run -d -p 9090:9090 --restart=always --name prometheus prom/prometheus
如果创建时未指定 --restart=always,可通过update 命令设置。
docker update --restart=always 容器ID(或者容器名)
(容器ID或者容器名根据实际情况修改)
并未使用 -v 挂载数据卷,配置项需要进入到容器内部中设置,生产环境可以将配置文件挂载在宿主机。
配置文件位于 /etc/prometheus 下,即 prometheus.yaml 。
添加拉取地址
###以下内容为SpringBoot应用配置
- job_name: 'api'
scrape_interval: 5s
metrics_path: '/testMonitor/prometheus'
static_configs:
- targets: ['192.168.x.x:30000']
配置完,拉取地址后,重启容器即可。
查看信息
http://localhost:9090/targets?search=
3.2、grafana
相关文档
官网:Run Grafana Docker image | Grafana documentation
启动命令
无需指定 grafana 版本,使用最新启动即可,另外启动时,设置容器跟随 docker 生命周期。
docker run -d -p 3000:3000 --restart=always --name grafana grafana/grafana
进入 grafana
http://localhost:3000/login,默认账号密码 admin/admin。
添加 Datasource
http://localhost:3000/datasources/new
填写 url 。
保存并测试连接。
导入合适的模板
去模板市场选择合适的模板:Dashboards | Grafana Labs 。
导入模板 8919 与 16144 。