欢迎光临
我们一直在努力

php方案 API监控

API 监控

大白话:盯着你的接口,一旦挂了/慢了/报错了,立刻告警。

—–
监控什么?

可用性 → 接口还活着吗?(HTTP 200 ?)
响应时间 → 有没有超时变慢?
错误率 → 5xx 报错多不多?
业务指标 → 返回的数据对不对?

—–
最简单的自监控(PHP)

<?php
// monitor.php — 定时任务每分钟跑一次

function checkApi(string $url, int $maxMs = 1000): void
{
$start = microtime(true);
$resp = @file_get_contents($url);
$ms = (int)((microtime(true) – $start) * 1000);

$ok = $resp !== false && $ms < $maxMs;

if (!$ok) {
mail('ops@example.com', "API 挂了: $url", "耗时: {$ms}ms");
}

// 写日志
file_put_contents('monitor.log', date('Y-m-d H:i:s') . " $url {$ms}ms " . ($ok ? 'OK' : 'FAIL') . "\\n",
FILE_APPEND);
}

checkApi('https://api.example.com/health');
checkApi('https://api.example.com/users', 500);

—–
生产级方案(推荐直接用现成工具)

Prometheus + Grafana → 指标采集 + 可视化大盘
Alertmanager → 告警规则(慢了/挂了发钉钉/微信)
Sentry → 捕获异常和错误堆栈
Uptime Kuma → 轻量级可用性监控,自部署

—–
健康检查接口(标配)

// GET /health
app()->get('/health', function() {
return [
'status' => 'ok',
'db' => DB::ping() ? 'ok' : 'fail',
'time' => date('c'),
];
});

监控系统每隔 30s 请求这个接口,挂了立刻知道。

—–
核心思路: 别等用户投诉,要在用户发现之前自己先发现。

赞(0)
未经允许不得转载:171主机测评 » php方案 API监控
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址