Prometheus 是当今业界最受欢迎的开源监控解决方案之一。它提供了一个完整的系统监控和警告工具包,专门用于记录实时的时间序列数据。这些数据可以涉及从操作系统的核心指标到自定义应用程序的性能统计数据。
在本文中,我们将深入探讨 Prometheus 的核心功能,并提供一个简单的 Java 应用程序的监控示例。
Prometheus 的核心特点
-
多维度数据模型:与传统的按照主机或实例组织的数据不同,Prometheus 的数据模型允许任意的键/值对作为标签。
-
Powerful Query Language (PromQL):这使得在查询时可以很容易地进行切片和切块,根据多个维度对数据进行筛选和聚合。
-
与多种模式的警报处理高度集成:这使得当满足某些条件时可以触发警报。
实践:使用 Prometheus 监控 Java 应用程序
我们将使用一个简单的 Java Spring Boot 应用程序作为例子。
- 添加 Prometheus 的 Java 客户端库
在 Maven 的 pom.xml 中添加以下依赖:
<dependency>
<groupId>io.prometheus</groupId>
<artifactId>simpleclient</artifactId>
<version>0.9.0</version>
</dependency>
<dependency>
<groupId>io.prometheus</groupId>
<artifactId>simpleclient_spring_boot</artifactId>
<version>0.9.0</version>
</dependency>
<dependency>
<groupId>io.prometheus</groupId>
<artifactId>simpleclient_httpserver</artifactId>
<version>0.9.0</version>
</dependency>
- 为你的应用程序暴露 Prometheus 指标
import io.prometheus.client.Counter;
import io.prometheus.client.spring.boot.EnablePrometheusEndpoint;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnablePrometheusEndpoint
public class MyApplication {
private static final Counter requests = Counter.build()
.name("requests_total").help("Total requests.").register();
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
每次请求都会增加 requests_total 计数器。
- 在 Prometheus 中配置你的 Java 应用程序
编辑 Prometheus 的配置文件 prometheus.yml,添加以下内容:
scrape_configs:
- job_name: 'java-application'
static_configs:
- targets: ['localhost:8080']
这告诉 Prometheus 从 Java 应用程序收集数据。
- 使用 Grafana 可视化数据
设置 Grafana
- 安装 Grafana
根据你的操作系统,从 Grafana 官网 下载并安装 Grafana。
- 启动 Grafana
运行 Grafana 后,访问 http://localhost:3000/。默认用户名和密码均为 admin。
- 添加 Prometheus 数据源
点击左侧菜单中的齿轮图标 ➡ 数据源 ➡ 添加数据源,选择 Prometheus。设置以下参数:
- URL:
http://localhost:9090(如果你的 Prometheus 在其他地址,请更改它) - Access:
Server
点击 "Save & Test"。
创建仪表板
- 添加新的 Dashboard
点击左侧菜单的 "+" ➡ Dashboard。
- 添加 Panel
在新的 Dashboard 上,点击 "Add Panel"。在查询编辑器中,选择 Prometheus 数据源并输入你的 PromQL 查询。例如,如果你在 Java 应用中监控了请求次数,你可以查询:
requests_total
- 调整面板设置
点击 Panel 标题 ➡ Edit,你可以修改面板的标题、描述和许多其他设置。利用 Grafana 的丰富功能,例如图表、表格、单统计等,根据需要定制面板的显示。
- 设置警报
Grafana 允许你为指标设置警报。点击 "Alert" 选项卡 ➡ "Create Alert"。你可以定义警报规则、评估时间间隔以及触发条件。
例如,如果你的应用请求超过某个阈值,可以设置警报通知你。
总结
Prometheus 和 Grafana 的结合提供了一个无与伦比的工具套件,用于监控、查询和可视化时间序列数据。这只是冰山一角,这两个工具的真正威力在于它们能够轻松集成并扩展到几乎任何应用和基础设施组件中。在你的 DevOps 旅程中,深入了解并掌握它们将为你提供巨大的价值。
Prometheus 与 Grafana 完美集成,您可以使用 Grafana 构建仪表板并可视化从 Prometheus 收集的数据。