使用IHealthChecksPublisher实现推送到Prometheus Pushgateway?

解读

国内微服务普遍采用 Prometheus + Grafana 做监控,但 Prometheus 默认是“拉”模式。对于短生命周期容器(Job、CronJob、FaaS)或防火墙内网服务,只能由服务主动“推”到 Pushgateway,再由 Prometheus 抓取。
.NET 健康检查体系在 3.x 之后内置了 IHealthCheck 与 IHealthChecksPublisher 两个扩展点:

  • IHealthCheck 负责“采集”
  • IHealthChecksPublisher 负责“上报”

因此题目本质考察:

  1. 是否理解健康检查生命周期(DI 范围、执行频率、序列化格式)
  2. 是否能把官方接口与 Prometheus 文本格式对齐(metric 名、label、HELP、TYPE、时间戳)
  3. 是否能在高并发场景下保证 Pushgateway 幂等、无内存泄漏、可观测、可灰度

国内面试常追问:

  • 为什么不用 pull 而要用 push?
  • 如果 Pushgateway 挂了怎么办?
  • 如何区分实例(instance、job)?
  • 如何与 k8s liveness/readiness 探针共存?

答到这些点才能体现“企业级落地经验”。

知识点

  1. IHealthChecksPublisher 接口定义

    • Task PublishAsync(HealthReport report, CancellationToken cancellationToken)
    • 注册为 Singleton,由 HealthCheckService 定时调用(默认 30 s,可配 HealthCheckPublisherOptions.Delay/Period)
  2. Prometheus 文本格式规范

    • 必须以 # HELP 与 # TYPE 开头
    • 指标名只能 [a-zA-Z_:][a-zA-Z0-9_:]*
    • Label 值需转义 \n " \
    • 可选时间戳,单位毫秒
  3. Pushgateway HTTP API

    • PUT /metrics/job/<job>/instance/<instance> 全量替换
    • POST 增量
    • DELETE 清理
    • 返回 202 Accepted 即成功,超时建议 5 s 以内
  4. 依赖注入与配置

    • 使用 IOptionsMonitor<PushgatewayOptions> 支持热重载
    • 采用 IHttpClientFactory + Polly 做重试、熔断,防止 publisher 拖垮主服务
  5. 标签设计(国内规范)

    • job=“apiservice”
    • instance=“pod-ip:port” 或 “hostName”
    • 额外可扩展 cluster、namespace、version,方便多环境聚合
  6. 指标命名

    • 推荐 health_status{service="foo"} 0/1
    • 也可细化 health_check_duration_seconds{check="sql"}
  7. 生命周期管理

    • 实现 IDisposable 释放 HttpClient、Timer
    • 在 k8s PreStop 钩子中发送 DELETE,防止旧实例指标残留

答案

  1. 定义配置节
public class PushgatewayOptions
{
    public string Endpoint { get; set; } = "http://pushgateway:9091/metrics";
    public string Job { get; set; } = "apiservice";
    public string Instance { get; set; } = $"{Environment.MachineName}:{Environment.ProcessId}";
    public int TimeoutSeconds { get; set; } = 5;
}
  1. 实现 Publisher
public sealed class PrometheusPushgatewayPublisher : IHealthChecksPublisher, IDisposable
{
    private readonly PushgatewayOptions _opt;
    private readonly HttpClient _http;
    private readonly ILogger<PrometheusPushgatewayPublisher> _log;

    public PrometheusPushgatewayPublisher(IOptions<PushgatewayOptions> opt,
                                          IHttpClientFactory factory,
                                          ILogger<PrometheusPushgatewayPublisher> log)
    {
        _opt = opt.Value;
        _http = factory.CreateClient("push");
        _http.Timeout = TimeSpan.FromSeconds(_opt.TimeoutSeconds);
        _log = log;
    }

    public async Task PublishAsync(HealthReport report, CancellationToken ct)
    {
        var payload = BuildMetrics(report);
        var url = $"{_opt.Endpoint}/job/{_opt.Job}/instance/{_opt.Instance}";

        using var req = new HttpRequestMessage(HttpMethod.Put, url);
        req.Content = new StringContent(payload, Encoding.UTF8, "text/plain");
        using var res = await _http.SendAsync(req, ct);

        if (!res.IsSuccessStatusCode)
            _log.Error("Pushgateway returned {StatusCode}", res.StatusCode);
    }

    private static string BuildMetrics(HealthReport report)
    {
        var sb = new StringBuilder();
        sb.AppendLine("# HELP health_status Health status 0=Unhealthy 1=Degraded 2=Healthy");
        sb.AppendLine("# TYPE health_status gauge");

        int overall = report.Status switch
        {
            HealthStatus.Healthy   => 2,
            HealthStatus.Degraded  => 1,
            HealthStatus.Unhealthy => 0,
            _ => 0
        };
        sb.AppendLine($"health_status{{check=\"overall\"}} {overall} {report.TotalDuration.TotalMilliseconds}");

        foreach (var kv in report.Entries)
        {
            int value = kv.Value.Status switch
            {
                HealthStatus.Healthy   => 2,
                HealthStatus.Degraded  => 1,
                _ => 0
            };
            var name = kv.Key.Replace("-", "_");
            sb.AppendLine($"health_status{{check=\"{name}\"}} {value} {kv.Value.Duration.TotalMilliseconds}");
        }
        return sb.ToString();
    }

    public void Dispose() => _http?.Dispose();
}
  1. 注册
services.Configure<PushgatewayOptions>(Configuration.GetSection("Pushgateway"));
services.AddHttpClient("push");
services.AddSingleton<IHealthChecksPublisher, PrometheusPushgatewayPublisher>();
  1. appsettings.json
"Pushgateway": {
  "Endpoint": "http://pushgateway:9091/metrics",
  "Job": "order-api",
  "Instance": ""
}
  1. k8s 部署补充
  • 在 Deployment env 中给 Instance 注入 $(POD_IP):$(POD_PORT)
  • PreStop 钩子调用 curl -X DELETE http://pushgateway:9091/metrics/job/order-api/instance/$POD_IP:$POD_PORT
  • Prometheus 配置 honor_labels: true 防止 job/instance 被重写

至此,服务每次执行健康检查后自动把 0/1 指标推送到 Pushgateway,Prometheus 定时拉取即可在 Grafana 绘制“服务整体健康分”与“各检查项健康分”。

拓展思考

  1. 多集群灰度
    在 label 里加上 cluster=sh1/sh2,Grafana 变量联动,可实现按集群灰度重启观察健康分变化。

  2. 指标膨胀治理
    若检查项动态变化(如带版本号),需做 label 基数评估;超过 Pushgateway 默认 1000 条指标/分组 会 413,需要拆分 job 或聚合。

  3. 高可用方案
    Pushgateway 本身无 HA,可在 k8s 用 StatefulSet + 本地盘或 Thanos Receive 做远程写;或者直接在服务内暴露 /metrics,用 Prometheus Operator 的 Probe CRD 做 pull,完全去掉 Pushgateway。

  4. 安全加固
    给 Pushgateway 配 basic-auth 或 nginx ingress + mTLS;在 publisher 侧用 Secret 存密码,通过 HttpClientHandler 注入 NetworkCredential。

  5. 与 OpenTelemetry 统一
    .NET 8 已支持 OTLP Exporter,可把 health_status 作为 Gauge 打到 OTEL Collector,再由 exporter 转发到 Prometheus,避免维护私有 publisher,但需评估 Collector 部署成本。

掌握以上扩展,可在面试中从“能跑”聊到“可维护、可扩展、可灰度、可治理”,体现资深工程师的端到端落地能力。