news 2026/4/17 14:33:22

Hyper方案 服务监控告警(Prometheus + Grafana)

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
Hyper方案 服务监控告警(Prometheus + Grafana)
Hyperf 官方内置 hyperf/metric,原生支持 Prometheus,零侵入自动采集。 --- 安装composerrequire hyperf/metric php bin/hyperf.php vendor:publish--id=hyperf.metric ---1. 配置 config/autoload/metric.php:<?phpreturn['default'=>env('METRIC_DRIVER','prometheus'),'use_standalone_process'=>true, // 独立进程采集,不影响业务'metric'=>['prometheus'=>['driver'=>\Hyperf\Metric\Adapter\Prometheus\MetricFactory::class,'mode'=>\Hyperf\Metric\Adapter\Prometheus\Constants::SCRAPE_MODE,'namespace'=>env('APP_NAME','hyperf'),'scrape_host'=>'0.0.0.0','scrape_port'=>9502,'scrape_path'=>'/metrics',],],];---2. 自动采集(零代码) 框架自动采集以下指标,无需任何代码: hyperf_http_requests_total# HTTP 请求总数hyperf_http_request_duration_ms# 请求耗时分布hyperf_db_query_duration_ms# DB 查询耗时hyperf_redis_commands_total# Redis 命令数hyperf_coroutine_count# 协程数量hyperf_worker_memory_bytes# Worker 内存---3. 业务自定义指标<?php namespace App\Service;use Hyperf\Di\Annotation\Inject;use Hyperf\Metric\Contract\MetricFactoryInterface;class OrderService{#[Inject]private MetricFactoryInterface$metric;publicfunctioncreateOrder(int$userId, array$items): array{$timer=$this->metric->makeHistogram(name:'order_create_duration_ms', labelNames:['status'],)->startTimer();try{$order=Order::create(['user_id'=>$userId,'total'=>collect($items)->sum('price'),]);// 订单计数$this->metric->makeCounter('orders_total',['status'])->with('success')->add(1);// 订单金额分布$this->metric->makeHistogram('order_amount',['currency'])->with('CNY')->observe($order->total);return$order->toArray();}catch(\Throwable$e){$this->metric->makeCounter('orders_total',['status'])->with('failed')->add(1);throw$e;}finally{$timer->end(['status'=>isset($order)?'success':'failed']);}}}---4. 告警中间件(慢请求 + 错误率)<?php namespace App\Middleware;use Hyperf\Metric\Contract\MetricFactoryInterface;use Psr\Http\Message\ResponseInterface;use Psr\Http\Message\ServerRequestInterface;use Psr\Http\Server\MiddlewareInterface;use Psr\Http\Server\RequestHandlerInterface;class MetricMiddleware implements MiddlewareInterface{publicfunction__construct(private MetricFactoryInterface$metric){}publicfunctionprocess(ServerRequestInterface$request, RequestHandlerInterface$handler): ResponseInterface{$start=microtime(true);$path=$request->getUri()->getPath();try{$response=$handler->handle($request);$status=$response->getStatusCode();}catch(\Throwable$e){$status=500;throw$e;}finally{$duration=(microtime(true)-$start)*1000;$this->metric->makeHistogram('http_duration_ms',['path','status'])->with($path,(string)$status)->observe($duration);$this->metric->makeCounter('http_requests_total',['path','status'])->with($path,(string)$status)->add(1);}return$response;}}---5. Docker Compose(完整监控栈) services: prometheus: image: prom/prometheus:latest volumes: - ./prometheus.yml:/etc/prometheus/prometheus.yml ports: -"9090:9090"grafana: image: grafana/grafana:latest ports: -"3000:3000"environment: GF_SECURITY_ADMIN_PASSWORD: admin volumes: - grafana_data:/var/lib/grafana alertmanager: image: prom/alertmanager:latest volumes: - ./alertmanager.yml:/etc/alertmanager/alertmanager.yml ports: -"9093:9093"volumes: grafana_data: prometheus.yml: global: scrape_interval: 15s scrape_configs: - job_name: hyperf static_configs: - targets:['host.docker.internal:9502']rule_files: - alerts.yml alerting: alertmanagers: - static_configs: - targets:['alertmanager:9093']---6. 告警规则 alerts.yml: groups: - name: hyperf rules:# 错误率 > 5%- alert: HighErrorRate expr:|rate(http_requests_total{status=~"5.."}[5m])/ rate(http_requests_total[5m])>0.05for: 2m labels: severity: critical annotations: summary:"Error rate {{$value| humanizePercentage }}"# P99 延迟 > 1s- alert: SlowResponse expr:|histogram_quantile(0.99, rate(http_duration_ms_bucket[5m]))>1000for: 5m labels: severity: warning annotations: summary:"P99 latency {{$value}}ms"# 内存 > 512MB- alert: HighMemory expr: hyperf_worker_memory_bytes>536870912for: 5m labels: severity: warning alertmanager.yml(钉钉/企微通知): route: receiver: dingtalk receivers: - name: dingtalk webhook_configs: - url:'http://dingtalk-webhook/dingtalk/robot1/send'send_resolved:true--- 核心要点: - use_standalone_process:true独立进程暴露 /metrics,不占用业务端口 - 框架自动采集覆盖80% 场景,只需对核心业务补充自定义指标 - 告警阈值:错误率5%、P99>1s、内存>512MB 是生产常用起点 - Grafana 直接导入 Dashboard ID11316(Hyperf 社区模板)
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/17 14:30:14

LGTV Companion:如何让LG电视与Windows电脑实现智能联动自动化?

LGTV Companion&#xff1a;如何让LG电视与Windows电脑实现智能联动自动化&#xff1f; 【免费下载链接】LGTVCompanion Power On and Off WebOS LG TVs together with your PC 项目地址: https://gitcode.com/gh_mirrors/lg/LGTVCompanion 想象一下这样的场景&#xff…

作者头像 李华
网站建设 2026/4/17 14:30:13

B站视频批量上传神器:Python自动化投稿终极指南

B站视频批量上传神器&#xff1a;Python自动化投稿终极指南 【免费下载链接】BilibiliUploader 模拟Bilibili windows投稿客户端 项目地址: https://gitcode.com/gh_mirrors/bi/BilibiliUploader 在内容创作日益繁荣的时代&#xff0c;B站UP主们面临着海量视频上传的挑战…

作者头像 李华
网站建设 2026/4/17 14:26:15

5个步骤掌握Windhawk:Windows系统模块化定制完全指南

5个步骤掌握Windhawk&#xff1a;Windows系统模块化定制完全指南 【免费下载链接】windhawk The customization marketplace for Windows programs: https://windhawk.net/ 项目地址: https://gitcode.com/gh_mirrors/wi/windhawk Windhawk是一个创新的Windows程序定制平…

作者头像 李华
网站建设 2026/4/17 14:26:10

别花冤枉钱!毕业论文工具这样搭配,查重+AIGC一次过

根据2026年最新市场数据和用户反馈&#xff0c;目前智能写作论文工具市场已进入“查重与AIGC双检”时代。毕业之家凭借“真实文献引用”和“学术合规”稳居国产毕业论文工具首选&#xff0c;而PaperRed则在“AIGC降痕”和“智能可视化”领域表现突出。 以下是这两款核心软件的…

作者头像 李华
网站建设 2026/4/17 14:25:10

从源码到系统:Linux环境下grpc_cpp_plugin的编译与集成实战

1. 为什么需要grpc_cpp_plugin&#xff1f; 在C项目中使用gRPC进行通信时&#xff0c;我们通常会先编写.proto文件定义服务接口。但光有接口定义还不够&#xff0c;还需要生成对应的C代码——这就是grpc_cpp_plugin的作用。它作为protobuf编译器的插件&#xff0c;能将.proto文…

作者头像 李华
网站建设 2026/4/17 14:23:21

WindowResizer终极指南:免费强制调整任意窗口大小的完整解决方案

WindowResizer终极指南&#xff1a;免费强制调整任意窗口大小的完整解决方案 【免费下载链接】WindowResizer 一个可以强制调整应用程序窗口大小的工具 项目地址: https://gitcode.com/gh_mirrors/wi/WindowResizer 你是否经常遇到那些无法正常拖拽调整大小的应用程序窗…

作者头像 李华