[修改]优化了了CPU占用率与内存占用显示

This commit is contained in:
makotocc0107
2024-08-30 14:25:27 +08:00
committed by Coding
parent 500c0f9f7d
commit a70f667e9e
2 changed files with 79 additions and 27 deletions

View File

@@ -7,41 +7,52 @@ use Filament\Widgets\ChartWidget;
class CPUStatus extends ChartWidget
{
protected static ?int $sort = 4;
protected static ?string $heading = 'CPU 占用率';
protected static ?int $sort = 5;
protected int | string | array $columnSpan = '1';
private const MAX_POINTS = 6;
protected function getData(): array
{
$prometheus = new PrometheusService();
// 查询 CPU 使用率数据,获取最近 60 秒内的平均值
$query = '100 - (avg by(instance) (rate(node_cpu_seconds_total{mode="idle"}[60s])) * 100)';
$cpuUsageResult = $prometheus->query($query);
// 查询过去 1 分钟内的每秒 CPU 用率数据
$cpuUsageRange = $prometheus->queryRange(
'100 - (avg by(instance) (rate(node_cpu_seconds_total{mode="idle"}[1m])) * 100)',
now()->subMinutes(1)->timestamp,
now()->timestamp,
1 // 每秒一个数据点
);
// 计算使用率和空闲率
$cpuUsage = 0;
if (isset($cpuUsageResult['data']['result'][0]['value'][1])) {
$cpuUsage = floatval($cpuUsageResult['data']['result'][0]['value'][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 占用率,并保留两位小数
}
}
$cpuIdle = 100 - $cpuUsage;
$data = [
round($cpuUsage, 2),
round($cpuIdle, 2),
];
return [
'labels' => ['CPU 使用率', 'CPU 空闲率'],
'labels' => $labels,
'datasets' => [
[
'label' => 'CPU 占用情况',
'label' => 'CPU 占用率 (%)',
'data' => $data,
'backgroundColor' => ['#FF8080', '#E0F5B9'], // 柔和颜色
'borderColor' => ['#FF8080', '#E0F5B9'], // 边框颜色
'borderWidth' => 1, // 边框宽度
'borderColor' => '#FF0000',
'backgroundColor' => 'rgba(255, 0, 0, 0.2)',
'fill' => true,
'tension' => 0.2,
],
],
];
@@ -49,7 +60,20 @@ class CPUStatus extends ChartWidget
protected function getType(): string
{
return 'pie'; // 设置为
return 'line'; // 设置为折线
}
protected function getOptions(): array
{
return [
'scales' => [
'y' => [
'beginAtZero' => true,
'min' => 0,
'max' => 100,
],
],
];
}
protected function getPollingInterval(): ?string