mysql缓存浏览量,如何在不影响MySQL数据库的情况下跟踪网页浏览量

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 for low to moderate traffic. However, under high traffic, constant writes to the DB would result in high read/write contention and eventually bring down the DB.

I have read several QA's here on Stackoverflow and elsewhere, where MongoDB is suggested as an alternative. However, that choice ain't available and I must stick to MySQL. Furthermore, I do not have control over the Engine — MyISAM or InnoDB (InnoDB performs better due to row based locking instead of table, as in case of MyISAM).

Considering the above scenario, what's the best posible method to track pageviews without thrashing the DB (in DB or something else)? I would really appreciate an answer that provides code fragments as a starting point (if posible).

BTW, I am using PHP.

Update:

@fire has a good solution here. However, it requires use of memcache. I am, looking at something that could be easily implemented without requiring specific infra. This is for a module that could virtually be used in different hosting environments. On a second thought things that comes to my mind are some sort of cookie or file log based implementation. I am not sure how such implementation would work in practice. Any further inputs are really welcome.

解决方案

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);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值