gpt4 book ai didi

php - Mysql Counter代码优化

转载 作者:行者123 更新时间:2023-11-29 08:56:57 25 4
gpt4 key购买 nike

我有一个大型下载网站,我有一个代码可以更新每个下载,以跟踪有多少唯一的人下载每个文件以及有多少人查看该文件。

但是,代码工作正常,但是当我有大量流量时,代码会减慢网站速度,并允许 mysql 服务器使用大量资源。这段代码可以优化吗?

我很感激有人为我做这件事,无论是通过内部加入他们等。谢谢

<?php
#Gathers the client info

$agent = $_SERVER['HTTP_USER_AGENT'];
$brows = explode(" ",$agent);
$ubr = "$brows[0]";
$exptime = time() + 200;
$var = time();
$uip = user_ip();

$del = mysql_query("DELETE FROM log_hits WHERE exptime < '".$var."'");
$hits = mysql_fetch_array(mysql_query("SELECT * FROM user_downloads WHERE id='".$file_id."'"));

#Process unique download count
$u_check = DB::FetchArray(DB::Query("SELECT COUNT(*) FROM log_hits where browser='".$ubr."' and uip='".$uip."' and file_id='".$file_id."'"));
if($file_check[0]=="0")
{
$res3 = DB::Query("INSERT INTO log_hits SET browser='".$ubr."', uip='".$uip."', exptime='".$exptime."', file_id='".$file_id."'");
$unique = $hits[day_unique] + 1;
}else
{
$unique = $hits[day_unique];
}

#update regular hits to the file,
$week = $hits[weekly] + 1;
$hour = $hits[this_hour] + 1;
$todayx = $hits[today_hits] + 1;
$total = $hits[total] + 1;
$month = $hits[month] + 1;

$res3 = DB::Query("UPDATE `user_downloads` SET `day_unique`='{$unique}', `weekly`='{$week}', `this_hour`='{$hour}', `month`='{$month}', `total`='{$total}' , `today_hits`='{$todayx}' WHERE `id`='".$file_id."'") or die(mysql_error());
?>

最佳答案

您有 5 个查询只是为了更新一个或多或少简单的计数器。在我看来,这太过分了。

我不知道您的并发用户数量,但我建议采用以下方法:

  • 只需保留类似于当前 log_hits 表的下载日志即可。
  • 每隔一小时左右运行一个 cronjob 脚本来生成您需要的统计信息,并清除日志表中的旧条目(或将它们移到其他地方,具体取决于您是否仍然需要它们做其他事情)。

这会将每次下载的查询次数减少到一次。另一方面,统计 cronjob 每次只会使用单个(尽管更昂贵)查询来完成多个(更便宜)查询的工作。总的来说,这应该有助于提高页面的响应时间。

关于php - Mysql Counter代码优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9720781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com