对于不会损害负载下的数据库的实时唯一计数器,有什么好的做法?
4 回答
压力最小?将问题外包 :),例如,使用Google Analytics。
(不过,Google Analytics 不是实时的。其他分析工具提供商提供实时解决方案,例如,KISSmetrics)
If you're building a website and need counters there's plenty of free to use analytics (Google Analytics, Yahoo Analytics, etc) and counter services which can provide far more information than some simple counter script. This would be my recommendation.
However, if you are building something yourself and have control over the server you could use another tool for actually doing the counting. I have used memcache for this purpose as it supports the "add" and "increment" method, which when called after the other (due to restrictions on the use of the command) can create such high speed realtime counters.
Memcache is an extremely fast (200,000+ requests per second on a slow machine) memory caching solution but is not permanent storage. You will need another solution for storing the numbers counted.
This is my solution for such a task, added to the beginning of a request in its own function:
$m = new Memcache;
$m->addServer('localhost', 11211);
$cacheKey = "performance_".gmmktime();
// Add in case it doesn't exist, no compression, 1 hour timeout
$m->add($cacheKey, (int) 0, false, (60*60));
// Increment cache
$m->increment($cacheKey, (int) 1);
Changing the $cacheKey also allows you to count multiple different things.
I then have another piece of code which collects this information in a cron script each minute and adds it to a database. This solution also works across multiple machines, depending on your implementation needs, allowing for a scalable counter implementation.
Clearly this is only a simple example, but hopefully you can see its use. This code is in use on a large scale multi-server game service running PHP.
You might use a (custom) session handler that stores user-sessions in a database or a caching system, like APC or Memcached.
That way you could count the number of active sessions for your website (each visitor is given a unique session id).
You give sessions a very short session timeout, to prevent users being counted as 'active' even if they are no longer visiting your page.
By using sessions you'll be able to keep track of the number of people currently on your website, even if multiple people share the same IP-address
visitor_counter
具有行ip
和的数据库表when
。然后在每个页面加载时,检查用户的 ip 在给定时间内是否在数据库中when
(日期时间字段或包含时间戳的 int 字段)。如果 ip 在数据库中,则不要执行任何操作。如果不是,请添加它。然后根据自 以来经过的时间定期修剪值when
。您可以使用 COUNT(ip) 来计算访问者总数。
这可以调整为在最后 X 时间内显示访问者,您可以添加一个visits
字段来查看用户加载了多少页面等。
我不完全确定这将如何执行,但我认为理论上它可以满足您的需求。