Как решить проблему с высоким уровнем использования MySQL для виртуального хостинга.Хостинг для моего сайта был приостановлен из-за MYSQL High Usage - PullRequest
0 голосов
/ 16 февраля 2019

Сегодня внезапно мой хостинг для веб-сайта был приостановлен моим поставщиком услуг.Мне нужна помощь в поиске причины проблемы.Они прислали мне журналы, которыми поделились:-пул для push-уведомлений, который вызывает проблемы.

Вот код для уведомлений, используемых на каждой странице сайта.

      <script type="text/javascript">

    function poll() {
        var ajax = new XMLHttpRequest();
        ajax.onreadystatechange = function() {
            if (this.readyState === 4 && this.status === 200) {
                if (this.status === 200) {
                    try {
                        var json = JSON.parse(this.responseText);                       //alert('changed');
                    } catch {
                        setTimeout(poll,55000);return;
                    }


                    if (json.status !== true) {
                        alert(json.error);return;
                    }

                    var data = json.data;
                    for (var i = 0, len = data.length; i < len; i++) {
                        var x = data[i];
                        var body = 'Task: ' + x.content + '\nDate: ' + x.time + '\nID: ' + x.id;
                        notifyMe(body,x.id);
                    }




                    setTimeout(poll,55000);
                } else {
                    setTimeout(poll,55000);
                }

            }
        }
        ajax.open('GET', 'long-polling.php', true);
        ajax.send();


    }

    setTimeout(poll,60000);

//var body1 = "This is the body of the notification asargument";

function notifyMe(body1,id) {
  // Let's check if the browser supports notifications
  if (!("Notification" in window)) {
    alert("This browser does not support desktop notification");
  }

  // Let's check if the user is okay to get some notification
  else if (Notification.permission === "granted") {
    // If it's okay let's create a notification
  var options = {
        body: body1,
        icon: "icon.png",
        dir : "ltr"
    };
  var notification = new Notification("Task Alert",options);
    notification.addEventListener("click", function() {
    window.open('opentask.php?id='+id, '_blank');
    window.focus();
    this.close();
    // Do something cool

}, {once : true});

  }

  // Otherwise, we need to ask the user for permission
  // Note, Chrome does not implement the permission static property
  // So we have to check for NOT 'denied' instead of 'default'
  else if (Notification.permission !== 'denied') {
    Notification.requestPermission(function (permission) {
      // Whatever the user answers, we make sure we store the information
      if (!('permission' in Notification)) {
        Notification.permission = permission;
      }

      // If the user is okay, let's create a notification
      if (permission === "granted") {
        var options = {
              body: "Notifications enabled",
              icon: "icon.png",
              dir : "ltr"
          };
        var notification = new Notification("Notification",options);
      }
    });
  }

  // At last, if the user already denied any notification, and you
  // want to be respectful there is no need to bother them any more.
}
</script> 

Вот код для файла long-polling.php

<?php

//session_start();
session_write_close();
ignore_user_abort(false);
set_time_limit(40);

try {

    include_once '../config.php';

    if ($_COOKIE['notifyEnabled']==0) {
//      echo "<script>alert('Helow');</script>";
        $user = $_COOKIE['loggedinid'];

        // add user to the database
        $mysqli -> query("INSERT INTO tasks_update_track VALUES ($user, 0)");
        // send to the browser
        setcookie('notifyEnabled', 1);
        $_COOKIE['notifyEnabled']=1;
        // first request does not do anything than creating the cookie
        exit();
    }

    // get the user value 
    $user = $_COOKIE['loggedinid'];

    while (true) {

        // select new rows
        $result = $mysqli -> query("SELECT t.id, t.title, t.description , t.reminder FROM tasks t INNER JOIN tasks_update_track ud ON ud.last_sent_id < t.id WHERE ud.user_id = $user AND t.responsibleperson=$user ORDER BY t.id");

        // check whether there were new rows in above query
        if ($result && $result -> num_rows) {
            //if yes, makes the output
            $output = [];

            // this is used to update the db_user_data table at last. As rows are ordered by t.id in ascending order in above query, last row has the last Id
            $lastId = 0;
            foreach ($result as $row) {
                $output[] = [
                    'content' => $row['title'],
                    'id' => $row['id'], 
                    'time' => $row['reminder']];

                $lastId = $row['id'];
            }

            // update the table and set last_sent_id to the last sent row id of other table.
            $mysqli -> query("UPDATE tasks_update_track SET last_sent_id = $lastId WHERE user_id = $user");


            echo json_encode([
                'status' => true,
                'data' => $output
            ]);
            exit;
        }



        // db queries are heavy. So 2 seconds
        sleep(5);
    }

} catch (Exception $e) {

    exit(
        json_encode(
            array (
                'status' => false,
                'error' => $e -> getMessage()
            )
        )
    );

}
...