在 macOS 上部署 Grafana 和 Prometheus 来监控 Java 服务是一个非常实用的操作。以下是详细的步骤,包括如何安装和配置 Prometheus、Grafana 以及在 Java 服务中集成 Prometheus 的客户端库来收集指标数据。
1. 安装 Prometheus
1.1 使用 Homebrew 安装 Prometheus
首先,确保你已经安装了 Homebrew。然后运行以下命令来安装 Prometheus:
brew install prometheus
1.2 配置 Prometheus
安装完成后,编辑 Prometheus 的配置文件。默认配置文件路径为 /opt/homebrew/etc/prometheus.yml。
编辑 prometheus.yml
文件,添加你的 Java 服务的指标抓取配置:
global:
scrape_interval: 15s # 设置全局抓取间隔时间
# 配置抓取目标
scrape_configs:
- job_name: "java-server"
static_configs:
- targets: ["xxxxx:11011"]
metrics_path: /actuator/prometheus
- job_name: 'java-server-health'
static_configs:
- targets: ['xxxxx:11011']
metrics_path: /actuator/health
- job_name: 'prometheus'
static_configs:
- targets: ['127.0.0.1:9090']
1.3 启动 Prometheus
启动 Prometheus 服务:
brew services start prometheus
你也可以手动启动 Prometheus:
prometheus --config.file=/opt/homebrew/etc/prometheus.yml
2.安装 Grafana
2.1 使用 Homebrew 安装 Grafana
brew install grafana
2.2 启动 Grafana
启动 Grafana 服务:
brew services start grafana
你也可以手动启动 Grafana
grafana-server --config=/opt/homebrew/etc/grafana/grafana.ini --homepath=/opt/homebrew/opt/grafana/bin/grafana
/opt/homebrew/opt/grafana/bin/grafana server --config /opt/homebrew/etc/grafana/grafana.ini --homepath /opt/homebrew/opt/grafana/share/grafana --packaging\=brew cfg:default.paths.logs\=/opt/homebrew/var/log/grafana cfg:default.paths.data\=/opt/homebrew/var/lib/grafana cfg:default.paths.plugins\=/opt/homebrew/var/lib/grafana/plugins
3.配置 Java 服务
在 Java 服务中使用 micrometer
和 prometheus
客户端库来暴露指标。以下是一个 Spring Boot 应用的示例。
3.1 添加依赖
在你的 pom.xml
文件中添加 micrometer-registry-prometheus
依赖项:
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
<version>1.8.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
3.2 配置 Spring Boot 应用
在 application.properties
文件中配置 Spring Boot 应用暴露指标端点:
management.server.port=11011
management.endpoints.web.base-path=/actuator
management.endpoints.web.exposure.include=prometheus,health,info
management.endpoint.prometheus.enabled=true
management.metrics.export.prometheus.enabled=true
management.endpoint.health.show-details=always
management.endpoint.health.probes.enabled=true
management.metrics.tags.application=${app.id:${spring.application.name}}
3.3 启动 Spring Boot 应用
运行 Spring Boot 应用,默认情况下,Prometheus 指标将通过 /actuator/prometheus
端点暴露。
4.配置 Grafana
4.1 访问 Grafana
打开浏览器,访问 http://localhost:3000(默认端口)。使用默认的用户名和密码 admin/admin 登录。
4.2 添加 Prometheus 数据源
- 进入 Grafana 仪表板,点击左侧菜单中的“Configuration” -> “Data Sources”。
- 点击 “Add data source” 按钮。
- 选择 “Prometheus” 作为数据源类型。
- 在 “URL” 字段中输入 Prometheus 服务器地址,例如 http://localhost:9090。
- 点击 “Save & Test” 按钮以保存配置并测试连接。
4.3 创建仪表板
- 在 Grafana 中点击左侧菜单中的 “Create” -> “Dashboard”。
- 添加新面板(Panel),选择你的 Prometheus 数据源并输入 PromQL 查询来获取 Java 服务的指标。
- 配置图表的显示方式,然后保存仪表板。