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

Consul 与 Prometheus 集成实战:服务自动发现与监控配置指南(含 ThinkPHP8 示例)

Consul 介绍

Consul 是基于 GO 语言开发的开源工具,主要面向分布式、服务化的系统提供服务注册、服务发现和配置管理功能。它具备服务注册/发现、健康检查、Key/Value 存储、多数据中心支持及分布式一致性保证等能力。

此前通过 Prometheus 实现监控时,新增 Target 需修改服务器配置文件,即便使用 file_sd_configs 配置,也需登录服务器修改对应 Json 文件,操作繁琐。而 Prometheus 官方支持多种自动服务发现类型,其中就包括 Consul。

为什么需要 Consul 与 Prometheus 配合?

Prometheus 与 Consul 配合实现服务发现,核心是借助 Consul 的服务注册/发现能力,让 Prometheus 动态获取待监控的服务实例列表,避免手动配置目标(尤其适合微服务动态扩缩容场景)。

核心原理

  1. Consul 角色:作为服务注册中心,接收服务实例的注册(包含地址、端口、标签、健康状态等元数据),并提供 HTTP API 供查询服务列表。
  2. Prometheus 角色:通过配置 consul_sd_configs,定期调用 Consul 的 API 获取服务实例信息,动态生成监控目标,自动抓取指标。

实现步骤

  1. 安装并启动 Consul(默认端口 8500,提供服务注册/发现 API)。
  2. 安装 Prometheus(默认端口 9090,用于配置服务发现)。
  3. 准备待监控的服务(需暴露 metrics 端点,如 /metrics)。

Consul 安装部署

源码安装

我们仅需要 consul 可执行文件即可

./consul agent -dev

Prometheus 安装

Prometheus安装非常简单,使用docker仅需要不到10分钟即可

{% link Prometheus 安装部署, Prometheus 安装部署实战:Docker 方式与监控配置可视化流程, https://blog.kong.college/posts/22807/, https://image.kong.college/i/2025/09/09/spq9n6.png %}

健康检查脚本

启动 Consul

安装 pm2 脚本进程守护:

apt install npm

安装 pm2:

npm install pm2 -g

测试进程守护:

pm2 start "./consul agent -dev" --name "consul"

在这个启动项中,我们定义了配置文件目录 config-dir、监听地址 bind 以及预期启动节点 bootstrap-expect

pm2 start "./consul agent -config-dir=/etc/consul.d/ -client=0.0.0.0 --bind=192.168.87.250 -server  -bootstrap-expect=1" --name "consul"

为了安全,生成 Bootstrap:

安全是一种习惯

./consul acl bootstrap

生成 HTTP 检查(配置文件):

service {name = "ThinkPHP8"id = "php8.1"address = "192.168.87.177"port = 8080token = "d45af3b5-a433-fc4b-4ff8-b50411ca4bf3"tags = ["thinkphp8", "php8.1", "manage"]check {name = "ThinkPHP8check"http = "http://192.168.87.177:8080"interval = "15s"timeout = "15s"status = "200-299"}
}

重启进程

./consul reload -token=d45af3b5-a433-fc4b-4ff8-b50411ca4bf3

将 Consul 注册到 Prometheus

将 Prometheus 的配置文件复制出来,修改后再放回:

docker cp prometheus:/etc/prometheus/prometheus.yml $PWD

关键配置项:

scrape_configs:# The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.- job_name: "prometheus"# metrics_path defaults to '/metrics'# scheme defaults to 'http'.static_configs:- targets: ["localhost:9090"]# The label name is added as a label `label_name=<label_value>` to any timeseries scraped from this config.labels:app: "prometheus"- job_name: 'consul-prometheus'consul_sd_configs:- server: '192.168.87.250:8500'services: []token: d45af3b5-a433-fc4b-4ff8-b50411ca4bf3relabel_configs:- source_labels: [__meta_consul_service_tag_metrics_path]action: replacetarget_label: __metrics_path__regex: 'metrics-path=(.*)'- source_labels: [__meta_consul_service]action: keepregex: 'frontend.*'

将修改好的配置放回容器并重启容器

docker cp $PWD/prometheus.yml prometheus:/etc/prometheus/prometheus.yml
docker restart prometheus

到这里,Prometheus 已能识别 Consul 中注册的服务。但需在待检查的服务中配置控制器,以应对 Prometheus 的检查。此过程中,Consul 仅作为服务发现工具,实际检查由 Prometheus 执行。

创建 ThinkPHP8 检查示例

我们尝试在中间件中统计关于请求的花销、请求次数以及花费时间等参数。

中间件

<?php
namespace app\middleware;use think\facade\Cache;
use think\facade\Request;class MetricsMiddleware
{public function handle($request, \Closure $next){$startTime = microtime(true);$response = $next($request);Cache::inc('http_requests_total');$method = $request->method();$path = $request->pathinfo();$key = "http_requests_by_path{method=\"$method\",path=\"$path\"}";Cache::inc($key);$responseTime = round(microtime(true) - $startTime, 4);Cache::set("http_response_time{path=\"$path\"}", $responseTime);$costTime = ($startTime - $_SERVER['REQUEST_TIME_FLOAT']) * 1000;Cache::set("http_consumer_cost_time",$costTime);return $response;}
}

控制器

<?php
namespace app\controller;use think\facade\Cache;
use think\Response;class Metrics
{public function index(){$metrics = $this->collectMetrics();return Response::create($metrics, 'html')->header(['Content-Type' => 'text/plain; charset=utf-8']);}private function collectMetrics(){$totalRequests = Cache::get('http_requests_total', 0);$onlineUsers = rand(50, 200); $startTime = Cache::remember('app_start_time', function () {return time();}, 86400);$pathMethodMetrics = $this->getHttpRequestsByPath();$responseTimeMetrics = $this->getHttpResponseTime();$consumerCostTime = Cache::get('http_consumer_cost_time', 0);$metrics = <<<METRICS
# HELP http_requests_total 应用总请求数
# TYPE http_requests_total counter
http_requests_total $totalRequests# HELP online_users 当前在线用户数
# TYPE online_users gauge
online_users $onlineUsers# HELP app_start_time_seconds 应用启动时间(Unix时间戳)
# TYPE app_start_time_seconds gauge
app_start_time_seconds $startTime{$pathMethodMetrics}{$responseTimeMetrics}# HELP http_consumer_cost_time 请求从到达至响应完成的总耗时(毫秒)
# TYPE http_consumer_cost_time gauge
http_consumer_cost_time $consumerCostTime
METRICS;return $metrics;}/*** 处理按路径和方法统计的请求数指标*/private function getHttpRequestsByPath(){$keys = Cache::handler()->keys('http_requests_by_path*');$metrics = [];$metrics[] = "# HELP http_requests_by_path 按请求方法和路径统计的请求数";$metrics[] = "# TYPE http_requests_by_path counter";foreach ($keys as $key) {if (preg_match('/http_requests_by_path\{method="([^"]+)",path="([^"]+)"\}/', $key, $matches)) {$method = $matches[1]; $path = $matches[2];  $value = Cache::get($key, 0); $metrics[] = "http_requests_by_path{method=\"{$method}\",path=\"{$path}\"} {$value}";}}return implode("\n", $metrics);}/*** 处理按路径的响应时间指标*/private function getHttpResponseTime(){$keys = Cache::handler()->keys('http_response_time*');$metrics = [];$metrics[] = "# HELP http_response_time 按路径统计的响应时间(秒,保留4位小数)";$metrics[] = "# TYPE http_response_time gauge";foreach ($keys as $key) {if (preg_match('/http_response_time\{path="([^"]+)"\}/', $key, $matches)) {$path = $matches[1]; $value = Cache::get($key, 0); $metrics[] = "http_response_time{path=\"{$path}\"} {$value}";}}return implode("\n", $metrics);}
}

此时,Prometheus 关于 ThinkPHP 的检查已经可以正常进行了。在后续的检查中,我们可以使用 Consul 的 API,通过创建相应的业务完成自动化注册的流程。


过滤以及重写规则

我们发现,有一些不需要监测的项目被顺带放进面板中,此时可以使用 relabel_configs 进行重写。例如在本次例子中,我们可以以 Consul 的标签为例,去掉 Consul 本身的检查。

在 Prometheus 中,relabel_configs 是用于对服务发现获取的目标(Target)元数据进行标签重写、过滤、新增或删除的核心配置。它在目标被实际抓取前生效,能灵活处理服务发现(如 Consul、K8s 等)返回的元数据,实现目标筛选、标签标准化等需求。

核心配置项

relabel_configs 由一系列重写规则组成,每个规则包含以下关键参数(常用):

参数 作用
source_labels 从目标的元数据中提取的标签列表(如 [__meta_consul_tags, __address__]),多个标签用逗号分隔。
separator source_labels 有多个标签时,用于拼接它们的分隔符(默认是 ;)。
regex 用于匹配 source_labels 拼接后的值的正则表达式(默认是 (.*),即匹配任意内容)。
modulus source_labels 拼接后的值做哈希取模,用于分片(较少用)。
target_label 重写后要生成的目标标签名(仅在 action: replace 等需要生成新标签的场景使用)。
replacement 正则匹配后的替换值,可通过 $1$2 引用正则中的分组(默认是 $1)。
action 重写动作(核心),决定对匹配的目标做什么操作(如保留、丢弃、替换标签等)。

常用 action 动作及示例

action 是重写规则的核心,决定了对目标的处理逻辑,常见动作如下:

1. keep:保留匹配的目标

仅保留 source_labels 拼接后的值能匹配 regex 的目标,其他目标会被过滤掉。

示例:只保留 Consul 服务标签中包含 php 的目标(对应你之前的配置):

relabel_configs:- source_labels: [__meta_consul_tags]  # 从Consul元数据中获取服务标签(如"php8.1,web")regex: .*php.*                       # 匹配包含"php"的标签action: keep                         # 保留匹配的目标

2. drop:丢弃匹配的目标

keep 相反,丢弃 source_labels 拼接后的值匹配 regex 的目标,保留其他目标。

示例:丢弃标签中包含 test 的目标(不监控测试环境服务):

relabel_configs:- source_labels: [__meta_consul_tags]regex: .*test.*action: drop  # 丢弃匹配的目标

3. replace:替换/新增标签

source_labels 匹配 regex 的值,通过 replacement 生成新值,并写入 target_label 指定的标签(若标签不存在则新增)。

示例1:将 Consul 服务名(__meta_consul_service)作为 app 标签:

relabel_configs:- source_labels: [__meta_consul_service]  # Consul服务名(如"thinkphp8")regex: (.*)                             # 匹配整个服务名target_label: app                       # 生成标签"app"replacement: $1                         # 用服务名作为标签值($1引用regex的第一个分组)action: replace

示例2:从目标地址(__address__,格式 ip:port)中提取 IP 作为 instance_ip 标签:

relabel_configs:- source_labels: [__address__]    # 目标地址,如"192.168.87.177:8080"regex: ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+):(.*)  # 分组1:IP,分组2:端口target_label: instance_ip       # 生成标签"instance_ip"replacement: $1                 # 用IP作为标签值action: replace

4. labelmap:批量映射标签

根据 regex 匹配现有标签名,将匹配的标签名替换为 replacement 中的值(常用于将元数据标签转为业务标签)。

示例:将 Consul 元数据中以 __meta_consul_tag_ 开头的标签(如 __meta_consul_tag_env=prod)转为 env=prod

relabel_configs:- regex: __meta_consul_tag_(.+)  # 匹配标签名(如"__meta_consul_tag_env")replacement: $1                # 提取分组1作为新标签名(如"env")action: labelmap               # 批量映射标签

5. labeldrop:删除指定标签

删除所有标签名匹配 regex 的标签(常用于清理不需要的元数据标签)。

示例:删除所有以 __meta_consul_ 开头的元数据标签(避免冗余):

relabel_configs:- regex: __meta_consul_.+  # 匹配所有Consul元数据标签action: labeldrop        # 删除匹配的标签

6. labelkeep:仅保留指定标签

labeldrop 相反,只保留标签名匹配 regex 的标签,删除其他所有标签。

示例:只保留 appinstancejob 三个标签:

relabel_configs:- regex: (app|instance|job)  # 仅匹配这三个标签action: labelkeep          # 保留匹配的标签,删除其他

7. hashmod:按哈希分片目标

将目标按 source_labels 哈希后取模,用于将目标分片到不同分组(如多 Prometheus 实例分片监控)。

示例:将目标按 __address__ 哈希后分为3组,只保留第1组:

relabel_configs:- source_labels: [__address__]modulus: 3          # 分为3组target_label: __shard__  # 生成分片标签action: hashmod- source_labels: [__shard__]regex: 0            # 只保留第1组(0是第1组,1是第2组,以此类推)action: keep

关键元数据标签(以 Consul 为例)

当使用 Consul 服务发现时,Prometheus 会自动为目标添加以下元数据标签(可通过 source_labels 引用):

元数据标签 含义
__meta_consul_address 服务注册的IP地址
__meta_consul_port 服务注册的端口
__meta_consul_service 服务名称(如"ThinkPHP8")
__meta_consul_tags 服务标签(逗号分隔,如"php8.1,web")
__meta_consul_node 服务所在的Consul节点名称
__address__ 目标地址(自动拼接为 ip:port
__metrics_path__ 指标抓取路径(默认 /metrics

例如:在 relabel_configs 中,定义从 tags 进行过滤,通过正则匹配 php 标签(如 ThinkPHP8),通过 action 字段指定保留逻辑。

其中 action 字段的参数说明:

  • replace:根据 regex 匹配 source_labels 标签的值(多个标签值按 separator 拼接),将匹配结果写入 target_label;支持用 ${1}, ${2} 引用正则分组;未匹配则不修改标签(默认动作)。
  • keep:丢弃 source_labels 值未匹配 regex 的 Target 实例。
  • drop:丢弃 source_labels 值匹配 regex 的 Target 实例。
  • hashmod:将 target_label 设置为 source_labels 的哈希取模结果。
  • labelmap:用 regex 匹配标签名,捕获内容作为新标签名,原标签值作为新标签值。
  • labeldrop:删除所有匹配 regex 的标签。
  • labelkeep:删除所有不匹配 regex 的标签。
  - job_name: 'consul-prometheus'consul_sd_configs:- server: '192.168.87.250:8500'services: []token: "d45af3b5-a433-fc4b-4ff8-b50411ca4bf3"relabel_configs:- source_labels: [__meta_consul_tags]regex: .*php.*action: keep

将配置文件更改后,发送回容器内部,会发现 Consul 本身不会出现在面板中:

docker cp $PWD/prometheus.yml prometheus:/etc/prometheus/prometheus.yml
docker restart prometheus

http://www.hskmm.com/?act=detail&tid=35877

相关文章:

  • 2025年TYPE-C母座厂家权威推荐榜:防水/板上/沉板/立插/卧式/侧贴/贴片式/插件式全系列,5A大电流高速TID认证接口一站式供应
  • 题解:P1196 [NOI2002] 银河英雄传说
  • Oracle下查询数据库SQL ID
  • 进程管理专题(一)
  • 使用SemaphoreSlim控制并发数
  • 杂题简述
  • css网格布局
  • 2025 年粘合剂厂家最新推荐排行榜:聚焦企业助力工业选品冷压球团/除尘灰/萤石粉/型煤/煤球粘合剂厂家推荐
  • 2025年流量控制阀厂家推荐排行榜,液压流量控制阀,气动流量控制阀,高压流量控制阀,精密流量控制阀批发公司推荐
  • 楼里网站开发完成,产品进入交代期
  • 比特币挖矿盈利能力9月下降超7%
  • 2025年医药冷链运输厂家权威推荐榜:药品/临床样本/CAR-T/蛋白/诊断试剂/生物制品/血液/细胞/芯片全程温控,冷藏车/冷藏箱/保温箱/干冰/液氮及国际冷链进出口专业服务
  • 2025 装修公司推荐排行榜单:江苏/浙江/制药厂/厂房/实验室/办公室/店面/净化室装修公司推荐,实测老客复购率与专业能力
  • 零代码改造 + 全链路追踪!Spring AI 最新可观测性详细解读
  • xupt 3g移动开发实验室二面
  • 2025年服饰厂家权威推荐榜:棒球帽,卫衣,羽绒服源头厂家精选,潮流设计与舒适品质口碑之选
  • 2025年10月北京昌平回龙观酒店推荐:对比评测榜助您锁定高性价比会议与度假之选
  • 2025年10月北京昌平回龙观酒店推荐榜:五家对比评测与实用选择指南
  • 2025 年最新华侨生联考培训机构口碑推荐榜:聚焦优质教学服务,助力考生高效备考,附详细选择指南
  • 洛谷题单指南-进阶数论-CF632D Longest Subsequence
  • 2025 年最新推荐锯床实力厂家排行榜:龙门 / 数控 / 金属带锯床等多类型设备权威甄选优质企业角度/金属带/双立柱/小型/大型锯床厂家推荐
  • 2025织带厂家权威推荐:东莞永沣专业定制防水织带与飞织鞋面
  • 2025发电机厂家实力推荐:三澳新能源科技专业制造,高效稳定动力解决方案
  • 2025年织带类厂家权威推荐榜:防水织带、鞋垫、编织包/针织包/飞织包包、松紧带、鞋带、织带、飞织鞋面源头企业精选
  • 2025年10月护眼台灯品牌评测推荐:十强榜单对比与理性选购指南
  • UV紫外相机在工业视觉检测中的应用 - 实践
  • 结对项目——实现一个自动生成小学四则运算题目的命令行程序
  • 2025 年最新推荐销轴厂家排行榜:含 8.8 级 / 4.8 级 / 10.9 级 / 镀锌 / 高强度 / 发黑 / 异型 / 非标 / 农机销轴公司推荐
  • 补贴防薅测试用例设计
  • 20232313 2025-2026-1 《网络与系统攻防技术》实验二实验报告 - 20232313