导购平台监控告警体系:Prometheus + Grafana + SkyWalking构建的全链路可观测性平台

大家好,我是高佣返利省赚客APP研发者微赚! 在复杂的微服务架构下,一次用户下单失败可能涉及网关鉴权、商品查询、订单创建、佣金计算及第三方联盟回调等十几个服务环节。传统的单体监控只能看到“服务器挂了”,却无法定位“哪行代码慢了”或“哪个SQL堵了”。为了实现对系统健康状态的毫秒级感知与精准故障定位,省赚客APP研发团队构建了基于Prometheus指标采集、Grafana可视化大屏以及SkyWalking分布式链路追踪的全链路可观测性平台。这套体系不仅覆盖了基础设施层,更深入到应用代码与业务逻辑层,让系统运行状态透明化。

一、Prometheus自定义指标埋点与采集

默认的JVM指标无法满足业务监控需求。我们需要实时掌握“佣金计算耗时”、“API接口QPS”、“外部联盟调用成功率”等关键业务指标。通过在Java代码中集成Micrometer库,我们将业务逻辑转化为Prometheus可识别的Time Series数据。

package cn.juwatech.monitor.metrics;

import cn.juwatech.cn.model.CommissionContext;
import cn.juwatech.cn.exception.CalculationException;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Timer;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class BusinessMetricsCollector {

    private final MeterRegistry registry;
    private final Timer commissionCalcTimer;
    private final Counter apiErrorCounter;
    private final Counter successCounter;

    public BusinessMetricsCollector(MeterRegistry registry) {
        this.registry = registry;
        
        // 定义佣金计算耗时计时器,按渠道打标签
        this.commissionCalcTimer = registry.timer("rebate.commission.calc.duration", 
            "service", "order-core", "type", "realtime");
        
        // 定义API错误计数器,区分错误类型
        this.apiErrorCounter = registry.counter("rebate.api.error.total", 
            "service", "gateway", "error_type", "timeout");
            
        this.successCounter = registry.counter("rebate.api.success.total");
    }

    /**
     * 带监控埋点的佣金计算逻辑
     */
    public double calculateWithMetrics(CommissionContext context) {
        return commissionCalcTimer.record(() -> {
            try {
                double amount = cn.juwatech.cn.service.CommissionEngine.compute(context);
                successCounter.increment();
                return amount;
            } catch (CalculationException e) {
                // 记录特定业务异常
                registry.counter("rebate.biz.exception", "code", e.getCode()).increment();
                throw e;
            } catch (Exception e) {
                apiErrorCounter.increment();
                throw new RuntimeException("System error", e);
            }
        }, TimeUnit.MILLISECONDS);
    }
}

通过上述代码,Prometheus能够实时拉取带有丰富标签(Tags)的指标数据,为后续的多维度聚合分析奠定基础。

二、SkyWalking无侵入式链路追踪

当请求在微服务间穿梭时,如何串联起整个调用链?我们引入Apache SkyWalking,利用Java Agent技术实现无侵入式的探针注入。它自动捕获HTTP、RPC、数据库及Redis调用,生成全局唯一的TraceID,完整还原请求路径。

package cn.juwatech.trace.context;

import cn.juwatech.cn.model.TraceInfo;
import org.apache.skywalking.apm.toolkit.trace.ActiveSpan;
import org.apache.skywalking.apm.toolkit.trace.Tag;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.springframework.stereotype.Service;

@Service
public class ExternalApiInvoker {

    /**
     * 使用SkyWalking注解标记关键业务跨度
     * @Tag 记录参数到链路日志
     * @OperationName 自定义跨度名称
     */
    @Trace(operationName = "invokeTaobaoUnionAPI")
    @Tag(key = "productId", value = "arg[0]")
    @Tag(key = "responseCode", value = "returnedObj.statusCode")
    public cn.juwatech.cn.model.TaobaoResponse fetchProductDetail(String productId) {
        // 手动添加自定义日志到Trace上下文,便于排查
        ActiveSpan.log("Starting to fetch product details for: " + productId);
        
        try {
            // 模拟远程调用
            cn.juwatech.cn.client.TaobaoClient client = new cn.juwatech.cn.client.TaobaoClient();
            cn.juwatech.cn.model.TaobaoResponse response = client.getProduct(productId);
            
            if (response == null || !response.isSuccess()) {
                ActiveSpan.error("Failed to fetch product data, status: " + (response != null ? response.getStatusCode() : "NULL"));
            }
            
            return response;
        } catch (Exception e) {
            // 记录异常堆栈到链路
            ActiveSpan.error(e);
            throw e;
        } finally {
            ActiveSpan.log("Finished API invocation");
        }
    }
    
    /**
     * 跨线程上下文传递示例
     */
    public void processAsyncTask(Runnable task) {
        // 确保子线程能继承主线程的TraceContext
        Runnable wrappedTask = cn.juwatech.cn.trace.ContextManager.wrap(task);
        new Thread(wrappedTask).start();
    }
}

通过@Trace@TagActiveSpan等工具类,开发人员可以精细化控制追踪粒度,将业务参数与错误堆栈直接关联到具体的Span上,极大缩短了故障排查时间。

三、Grafana多维可视化大屏与智能告警

采集到的指标与链路数据最终汇聚至Grafana进行展示。我们设计了分层级的监控大屏:从集群资源概览到核心业务黄金指标(延迟、流量、错误、饱和度)。同时,配置Prometheus Alertmanager实现分级告警。

# prometheus-alerts.yml 告警规则配置
groups:
  - name: rebate_critical_alerts
    rules:
      # 规则1:佣金计算接口P99延迟超过2秒持续1分钟
      - alert: HighCommissionLatency
        expr: histogram_quantile(0.99, rate(rebate_commission_calc_duration_seconds_bucket[5m])) > 2
        for: 1m
        labels:
          severity: critical
          team: order-system
        annotations:
          summary: "佣金计算接口延迟过高"
          description: "实例 {{ $labels.instance }} 的P99延迟达到 {{ $value }}s,可能影响用户到账体验。"
          
      # 规则2:淘宝联盟API调用错误率超过5%
      - alert: HighTaobaoAPIErrorRate
        expr: sum(rate(rebate_api_error_total{error_type="timeout"}[5m])) / sum(rate(rebate_api_success_total[5m])) > 0.05
        for: 2m
        labels:
          severity: warning
          team: integration
        annotations:
          summary: "第三方联盟接口异常"
          description: "淘宝联盟API错误率飙升至 {{ $value | humanizePercentage }},请立即检查网络或配额。"
package cn.juwatech.monitor.alert.handler;

import cn.juwatech.cn.model.AlertEvent;
import cn.juwatech.cn.service.NotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 接收Alertmanager推送的告警 webhook
 */
@RestController
public class AlertWebhookController {

    @Autowired
    private NotificationService notificationService;

    @PostMapping("/api/alerts/webhook")
    public void handleAlert(@RequestBody AlertEvent event) {
        // 根据告警级别路由通知渠道
        if ("critical".equals(event.getLabels().getSeverity())) {
            // 电话+短信通知值班人员
            notificationService.sendPhoneCall(event);
            notificationService.sendSms(event);
        } else if ("warning".equals(event.getLabels().getSeverity())) {
            // 钉钉/企业微信群机器人通知
            notificationService.sendDingTalk(event);
        }
        
        // 记录告警历史用于后续复盘
        cn.juwatech.cn.repository.AlertHistoryRepo.save(event);
    }
}

四、全链路可观测性的核心价值

通过Prometheus、Grafana与SkyWalking的深度融合,省赚客APP实现了从“黑盒运维”到“白盒洞察”的跨越。无论是底层CPU飙升,还是上层业务逻辑死锁,亦或是第三方接口抖动,系统都能在秒级内发现、定位并告警。这不仅保障了大促期间的系统稳定性,更通过数据驱动不断优化系统性能。可观测性已成为我们技术架构的基石,支撑着业务在高速轨道上稳健前行。

本文著作权归 省赚客app 研发团队,转载请注明出处!

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐