How to track pageviews without thrashing the MySQL DB

后端 未结 3 525
别跟我提以往
别跟我提以往 2021-02-06 04:07

I am trying to track pageviews in MySQL DB using the following query:

\"UPDATE $table SET pageviews = pageviews + 1 WHERE page_id = 1\"

This is fine

3条回答
  •  我寻月下人不归
    2021-02-06 04:35

    I would use memcached to store the count, and then sync it with the database on a cron...

    // Increment
    $page_id = 1;
    $memcache = new Memcache();
    $memcache->connect('localhost', 11211);
    
    if (!$memcache->get('page_' . $page_id)) {
        $memcache->set('page_' . $page_id, 1);
    }
    else {
        $memcache->increment('page_' . $page_id, 1);
    }
    
    // Cron
    if ($pageviews = $memcache->get('page_' . $page_id)) {
        $sql = "UPDATE pages SET pageviews = pageviews + " . $pageviews . " WHERE page_id = " . $page_id;
        mysql_query($sql);
        $memcache->delete('page_' . $page_id);
    }
    

提交回复
热议问题