【问题标题】:How to reduce mysql UPDATEs when viewing forum topics查看论坛主题时如何减少mysql更新
【发布时间】:2012-07-05 11:53:58
【问题描述】:

每次成员查看论坛上的主题/线程时,都会对主题表进行更新以将总查看次数增加一。

我正在寻找不更新每个视图的可能方法的答案,而是为每个主题积累视图和 - (如何?)添加视图,然后通过 cron 定期更新汇总视图 - (如何?)排队更新 - 其他选择?

【问题讨论】:

  • 你真的需要在主题表中存储视图计数吗?创建另一个 - 使用 topic, user, cnt 字段

标签: php mysql delay forum accumulate


【解决方案1】:

我建议使用Static variabletemp table 来维护计数,然后在一段时间内更新表格。

【讨论】:

  • 谢谢,我认为静态变量只会持续脚本的持续时间。由于有多个成员查看多个主题,因此不确定这是如何工作的。
  • 不是吗?静态是one per class。您可以将其存储到服务器重新启动之间,您可以将其保存到数据库并再次初始化。
【解决方案2】:

您可以尝试缓存主题视图的数量并通过 cron 每 X 分钟运行一次更新查询,或者检查每 N 个主题视图以运行查询。 为了让用户看到正确数量的主题/论坛视图,返回缓存值。
使用 APC

/*a small example using Topic ID and inc number*/
$TopicID=123;
if(apc_exists($TopicID)){
  echo "TotalViews : ".apc_inc($TopicID,1)."<br/>";
}else{
  // query database for numbers of views and cache that number, say its 10
 apc_store($TopicID,10);

 echo "TotalViews : ".apc_inc($TopicID,1)."<br/>";
}
/**********/
/*a larger example using a ForumIndex to hold all IDs, usefull for running a cron job and update Database*/
$ForumIndex = array(
        ("threads")=>array(
                (456) => 1000
        ),
        ("topics")=>array(
                (123)=>10
        )
);
if(apc_exists("forum_index")){ // if it exists
    $currentIndex = apc_fetch("forum_index");  // get current Index
    $currentIndex["topics"][] = array( // add a new topic 
        (1234)=>124
    );
    $currentIndex["threads"][456] += 1; // Increase threads with ID 456 by 1 view
    apc_store("forum_index",$currentIndex); // recache
    var_dump(apc_fetch("forum_index")); // view cached data
}else{ // it doesn't exists
    /*Fetch from database the value of the views */
        // Build $ForumIndex array and cache it
    apc_store("forum_index",$ForumIndex);
    var_dump(apc_fetch("forum_index"));
}
/*a cron job to run every 10 min to update stuff at database*/
if(apc_exists("forum_index")){
    $Index = apc_fetch("forum_index");
    foreach($Index as $ID => $totalViews){
        // execute update query
    }
    // delete cached data or do nothing and continue using cache
}else{
    echo "Ended cron job .. nothing to do";
}

【讨论】:

  • 谢谢。在发布问题之前,我试图找到一些缓存示例,但找不到与问题相关的任何内容。也许是不正确的关键词!每个主题都需要缓存其视图,这增加了复杂性。
  • 我不相信它那么复杂,存储一个带有主题/论坛 ID 的键,前缀或否(以避免冲突),并将视图值分配给它,而不是整个论坛/topics ids 将仅存储那些经常访问的主题/线程/论坛的缓存,除非您的论坛/主题在 10 分钟内被数千/数百万用户访问。添加了一些使用 APC 的小示例,希望它帮助
  • 谢谢 GeoPhoenix,我会投票给你,但我的低级别代表不允许。我目前正在使用 eaccelerator,所以可能是时候切换到 APC。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-28
  • 1970-01-01
  • 2023-01-15
  • 1970-01-01
  • 1970-01-01
  • 2011-01-01
  • 1970-01-01
相关资源
最近更新 更多