alan/yii2-metrics

There is no license information available for the latest version (v1.0.3) of this package.

yii2 framework metrics

v1.0.3 2023-04-12 07:10 UTC

This package is auto-updated.

Last update: 2024-04-12 09:16:40 UTC


README

接入步骤:

  1. 定义常量 YII_APP_NAME,该常量用于底层区分应用,由于我们经常使用yii2的高级框架,我建议定义在common配置文件下面common/config/main.php
defined('YII_APP_NAME') or define('YII_APP_NAME', 'myYiiApplication');
  1. 在主配置文件里面定义行为 建设配置在common/config/main.php
<?php
    return [
    'as metrics' => [
        'class' => yii2\metrics\filters\MetricsFilter::class,
        'appName' => YII_APP_NAME,
    ],
    'components' => [
        // 其它组件的配置
    ],
];
  1. 添加支持/metrics路由
<?php
namespace backend\controllers;

use yii\rest\Controller;
use yii2\metrics\MetricsTrait;

class MetricsController extends Controller {
	use MetricsTrait;
  public function behaviors(): array
  {
      $behaviors = parent::behaviors();
      $this->fillIpControllerBehavior($behaviors, ['127.0.0.1']);//允许访问访路由的ip白名单
      return $behaviors;
     }
}
  1. 上报rabbitmq任务数数据
use yii\console\Controller;
use yii2\metrics\MetricsTrait;

class  CrontabController extends Controller {
      /**
     * 上报rabbitMq任务剩余情况到prometheus
     */
    public function actionRabbitMqMetrics()
    {
        //此该填写了backend模块的id
        $factory = new \yii2\metrics\rabbitMq\Factory(YII_APP_NAME, 'app-backend');
        try {
            foreach ($factory->getIterator() as $task) {
                \yii2\crontab\base\Crontab::instance()->withTargetData($task)->withHandler($task)->run();
            }
        }catch (\Exception $exception) {
            echo sprintf("actionCheckQueues has exception msg:%s, at file:%s, at line: %d, trace: %s\n",
                $exception->getMessage(), $exception->getFile(), $exception->getLine(), '');
        }
    }

}
  1. 添加计划任务
# 商户上报mq任务数量
* * * * * php yii crontab/rabbit-mq-metrics