2012-07-05 54 views
0

每次成员查看论坛上的主题/线索时,都会在主题表上进行更新,以将总视图增加1。如何在查看论坛主题时减少mysql更新

我在回答可能的方法后,不对每个视图进行更新,而是累积每个主题的视图和 - (如何?)添加视图,然后通过cron定期更新总计视图 - (如何?)排队更新 - 其他选项?

+0

确实需要在主题表中存储查看次数吗?创建另一个 - 用'topic,user,cnt'字段 – k102 2012-07-05 11:55:41

回答

0

您可以尝试缓存主题视图的数量,并通过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"; 
} 
+0

谢谢。在发布问题之前,我试图找到一些缓存示例,但找不到与问题相关的任何内容。也许不正确的关键词!每个主题都需要缓存视图,这增加了复杂性。 – Competitions 2012-07-05 14:25:38

+0

我不相信它那复杂,存储一个关键的主题/论坛ID,前缀或否(为了避免冲突),并为其分配视图的价值,也不是整个论坛/主题ID将存储在只缓存那些经常访问的主题/主题/论坛,除非您在10分钟内通过千万/数百万用户访问论坛/主题。 使用APC添加了一些小例子,希望它有帮助 – Gntem 2012-07-05 16:51:30

+0

谢谢GeoPhoenix,我会投你一票,但我的低级代表不会允许。我目前正在使用eaccelerator,因此可能需要时间切换到APC。 – Competitions 2012-07-05 22:06:14

1

我建议使用Static variabletemp table维持计数和持续时间后更新表。

+0

谢谢,我认为静态变量只会持续脚本的持续时间。由于有多个成员查看多个主题,因此不确定这将如何工作。 – Competitions 2012-07-05 14:22:46

+0

是不是?静态是“每个类一个”。你可以存储它,直到服务器重新启动,你可以将它保存到数据库并重新初始化。 – manurajhada 2012-07-05 14:25:11

+0

如果有帮助,请不要忘记接受答案。 – manurajhada 2012-07-05 14:25:43