重复通知检查触发错误 508(检测到循环)

Repetitive Notif Checking triggers Error 508 (Loop Detected)

我调用 AJAX 来检查数据库是否每 3 秒或 10 秒有新的通知同时来自 4 个不同浏览器的相同查询。但是在循环 100+ 之后的某个时刻,服务器 returns 错误 508(检测到循环)。这只是一个简单的站点,所以我认为我不需要 VPS 服务器。

我在 SELECT 中添加了时间戳作为查询区分符,设置了 unset、flush、mysqli_free_result、pause、mysqli_kill、mysqli_close,但仍然出现错误。进入流程达到 20/20。

脚本

var counter = 1;
var notiftimer;

$(document).ready(function() {
    ajax_loadnotifs();
});

function ajax_loadnotifs() {
    $.ajax({
        type: "post",
        url: "service.php",
        dataType: "json",
        data: { action:'loadnotifs' },
        success: function(data, textStatus, jqXHR){
            $("div").append($("<p>").text(counter++ + ": succeeded"));

            notiftimer = setTimeout(function() {
                ajax_loadnotifs();
            }, 3000);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log(jqXHR.responseText);
        }
    });
}

service.php

$link = mysqli_connect('localhost', 'root', 'root', 'testdb');
$notifs = array();

$query = "SELECT id, message FROM notifs LIMIT 20";
if (!$temp_notifs = mysqli_query($link, $query)) {
    die(json_encode(array("errmsg" => "Selecting notifs.")));
}

while($notif = mysqli_fetch_assoc($temp_notifs)) {
    $notifs[] = $notif;
}

mysqli_close($link);        
echo json_encode($notifs);

cPanel - 资源使用概览

当输入进程达到 20/20 时,我收到错误 508。如何保持较低的服务器输入进程? (使用 4 种不同的浏览器进行测试,运行 它们都在共享主机上循环 100+。在本地计算机上没有问题

What is considered an Entry Processes?

An "Entry Process" is how many PHP scripts you have running at a single time.

来源:https://billing.stablehost.com/knowledgebase/186/What-is-considered-an-Entry-Processes.html

所以您发现的潜在问题最终是您同时 运行 太多进程。您可以采取一些措施来解决问题。

选项 1

寻找新的虚拟主机。这可能是最简单但也是最昂贵的,具体取决于您与当前房东的财务安排。找一个没有这个限制的。

选项 2

增加 ajax 个请求之间的时间间隔。为什么需要每 3 秒请求一次?那是非常非常短的时间。 15秒呢?还是30秒?或者见鬼,甚至 1 分钟?您的用户可能不需要像您想象的那样经常刷新数据。

选项 3

仅当当前 tab/window 处于焦点时才执行 ajax 调用。如果用户甚至没有查看您的页面,就没有理由继续轮询通知。

查看 Document.hasFocus()https://developer.mozilla.org/en-US/docs/Web/API/Document/hasFocus

选项 4

实施缓存层。如果你觉得你仍然需要非常非常频繁地请求数据,那么提高你检索这些数据的速度。如何实现缓存取决于您,但在某些情况下,即使使用文件 write/read 也可以减少完成请求所需的时间和资源。

从数据库中获取通知后,只需将 JSON 保存到一个文本文件中,然后从那里发送后续请求,直到数据库数据发生变化。看看这是否会提高性能。

如果您想更加专注于缓存,可以查看 Memcached (https://en.wikipedia.org/wiki/Memcached) or Redis (https://en.wikipedia.org/wiki/Redis) 等选项。

尝试组合多个选项以获得更好的性能!

事实证明,使用 https 而不是 http 和 AJAX 'get' 方法而不是 'post' 可以防止此错误。