目前,我将网站每小时的流量(输入请求总数)放在 MySQL 表中。我保留了过去 90 天的数据。
我想每小时检查一次,比如说第 6 个小时,看看流量是否比过去 7 天或过去 30 天的第 6 个小时流量增加/减少超过某个阈值。基本上,我看到了一种流量模式。不同的时间有不同的值。
为了生成警报,我想找到各种统计指标。阅读了一点后,我发现Statsd
可以用于此目的。
发送此类警报是否正确?有没有更好/更简单的解决方案?
我不打算构建任何仪表板。
我当前的数据如下:
+---------------------+---------------------+-----------+----------+
| startTime | endTime | component | traffic |
+---------------------+---------------------+-----------+----------+
| 2015-05-01 00:00:00 | 2015-05-01 01:00:00 | rest | 29090345 |
| 2015-05-01 01:00:00 | 2015-05-01 02:00:00 | rest | 32224087 |
| 2015-05-01 02:00:00 | 2015-05-01 03:00:00 | rest | 35165799 |
| 2015-05-01 03:00:00 | 2015-05-01 04:00:00 | rest | 36903464 |
| 2015-05-01 04:00:00 | 2015-05-01 05:00:00 | rest | 40394130 |
| 2015-05-01 05:00:00 | 2015-05-01 06:00:00 | rest | 44874862 |
| 2015-05-01 06:00:00 | 2015-05-01 07:00:00 | rest | 49988600 |
| 2015-05-01 07:00:00 | 2015-05-01 08:00:00 | rest | 52240544 |
| 2015-05-01 08:00:00 | 2015-05-01 09:00:00 | rest | 54517705 |
| 2015-05-01 09:00:00 | 2015-05-01 10:00:00 | rest | 55277967 |
| 2015-05-01 10:00:00 | 2015-05-01 11:00:00 | rest | 55285309 |
| 2015-05-01 11:00:00 | 2015-05-01 12:00:00 | rest | 55572614 |
答案1
答案2
您可以使用以下SQL脚本来比较流量。
set @threshold = 50; /*threshold for comparing the traffic*/
set @limit = 30 /*how many days to consider while generating avg value*/
/*calculate the time range, comparison is done for the last hour*/
set @end_time = current_timestamp();
set @end_time = timestamp(date(@end_time), maketime(hour(@end_time), 0, 0));
set @start_time = date_sub(@end_time, interval 1 hour);
/*find out the traffic for the last hour*/
select traffic
from test.traffic_stats
where startTime >= @start_time
and endTime <= @end_time
into @curr_traffic;
/*now find out the avg traffic for the past @limit days*/
select ifnull(avg(traffic), 0)
from test.traffic_stats
where startTime < @start_time
and startTime >= date_sub(@start_time, interval @limit day)
and time(startTime) >= time(@start_time)
and time(endTime) <= time(@end_time)
into @avg_traffic;
/*generate the report*/
select concat(
'Current traffic '
@curr_traffic,
' is '
if(@curr_traffic > @avg_traffic + @threshold,
'more',
if(@curr_traffic < @avg_traffic - @threshold,
'less',
'same'
)
),
' compared to the avg traffic ',
@avg_traffic
) as result;
该脚本将通过查询表生成基于过去 30 天平均流量的报告test.traffic_stats
。请修改脚本以满足您的要求。现在将此 SQL 脚本另存为,report.sql
您可以使用Cron
mysql 命令行以特定间隔运行它,如下所示。
mysql -hhost -uuser -ppassword -s <report.sql | awk '{print $1}'
这将提取结果并打印到标准输出。现在您可以使用 GNU Mailutils 将警报发送到您的电子邮件地址。
mail -s "$(mysql -hhost -uuser -ppassword -s <report.sql | awk '{print $1}')" [email protected]