queryRange( '100 - (avg by(instance) (rate(node_cpu_seconds_total{mode="idle"}[1m])) * 100)', now()->subMinutes(1)->timestamp, now()->timestamp, 1 // 每秒一个数据点 ); $labels = []; $data = []; if (!empty($cpuUsageRange['data']['result'][0]['values'])) { // 取出所有的数据点,以时间戳为键 $cpuValues = array_column($cpuUsageRange['data']['result'][0]['values'], 1, 0); // 只保留最新的 MAX_POINTS 个数据点 $timestamps = array_keys($cpuValues); $timestamps = array_slice($timestamps, -self::MAX_POINTS); date_default_timezone_set('Asia/Shanghai'); foreach ($timestamps as $timestamp) { $labels[] = date('H:i:s', $timestamp); // 格式化时间戳为小时:分钟:秒 $data[] = round(floatval($cpuValues[$timestamp]), 2); // 取出每个时间点的 CPU 占用率,并保留两位小数 } } return [ 'labels' => $labels, 'datasets' => [ [ 'label' => 'CPU 占用率 (%)', 'data' => $data, 'borderColor' => '#FF0000', 'backgroundColor' => 'rgba(255, 0, 0, 0.2)', 'fill' => true, 'tension' => 0.2, ], ], ]; } protected function getType(): string { return 'line'; // 设置为折线图 } protected function getOptions(): array { return [ 'scales' => [ 'y' => [ 'beginAtZero' => true, 'min' => 0, 'max' => 100, ], ], ]; } protected function getPollingInterval(): ?string { return '1s'; // 每秒更新一次 } }