【发布时间】:2021-11-05 15:40:10
【问题描述】:
嘿,我从我的 MySQL 数据库中用 PHP 制作了一个 API,它相当占用 CPU,并且每秒被调用多次。
$timer = $candle_time * 60;
$DATABASE_HOST = '';
$DATABASE_USER = '';
$DATABASE_PASS = '';
$DATABASE_NAME = '';
$response = array();
$link = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
$query = "SELECT * FROM table WHERE name LIKE 'name' ORDER BY table.datetime ASC";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_row($result)) {
$dates .= $row[1]. ',';
$price .= $row[2]. ",";
$datetime .= $row[3]. ',';
}
$dates = explode(",",$dates);
$price = explode(",",$price);
$datetime = explode(",",$datetime);
for($i = 0; $i < count($dates); $i++){
array_push($response,array(strtotime($datetime[$i]),$dates[$i],$price[$i]));
}
$counting_segments = 0;
$grouped_prices = array();
$final_grouping = array();
$rounded = ceil($response[0][0]/$timer)*$timer;
$counted = count($response)-1;
for($i = 0; $i < count($response); $i++){
if($i == $counted){
$rounded = ceil($previous_time/$timer)*$timer;
array_push($final_grouping,array($rounded,$grouped_prices));
}
if($response[$i][0] > $rounded){
$previous_time = $response[$i][0];
array_push($final_grouping,array($rounded,$grouped_prices));
$grouped_prices = array();
$rounded = ceil($response[$i][0]/$timer)*$timer;
}
if($response[$i][0] < $rounded){
$previous_time = $response[$i][0];
array_push($grouped_prices,$response[$i][2]);
} else {
array_push($grouped_prices,$response[$i][2]);
}
}
$new_array = array();
for($i = 0; $i < count($final_grouping); $i++){
$first_array = $final_grouping[$i][0];
$second_array = $final_grouping[$i][1];
$first_price = $second_array[0];
$last_price = end($second_array);
$high_price = max($second_array);
$low_price = min($second_array);
$final_date = $first_array;
$obj = new StdClass;
$obj->time = $final_date;
$obj->open = $first_price;
$obj->high = $high_price;
$obj->low = $low_price;
$obj->close = $last_price;
array_push($new_array,$obj);
}
$json_api = json_encode($new_array);
echo $json_api
我认为 503 的原因是它用于计算请求的 CPU 功率。有没有一种方法可以让我使用脚本或其他东西每秒提取数据并将其保存到 php 文件中以减轻负载,或者有更好的方法吗?
我确实亲自运行过它,它运行良好,但是随着越来越多的人向它提出请求,它经常提供 503。
谢谢。
【问题讨论】:
-
最昂贵的 CPU 是 MySQL 查询。尝试优化它或只是添加限制
-
除了一些相当低效的 PHP 代码之外,您还从数据库中检索了大量数据,然后您会反复查找第一个、最后一个最低和最高价格。更有针对性的查询可以直接提取该数据并节省大量工作量。
-
您也可以添加您的数据库结构吗?它会让观众更容易找到适合您的解决方案