且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何为网站编写高效的计数器

更新时间:2023-12-02 14:34:46

一个有趣的主题.增加一个计数器(可能很简单),只是已经是一个事务……这意味着,它可以将整个数据库锁定的时间超过了合理的时间!-)这很容易成为瓶颈整个系统.

A fascinating subject. Incrementing a counter, simple as it may be, just has to be a transaction... meaning, it can lock out the whole DB for longer than makes sense!-) It can easily be the bottleneck for the whole system.

如果您需要严格精确的计数,但又不需要立即更新它们,我最喜欢的方法是将可计数的信息附加到日志中(出于数据更新目的,经常切换日志).关闭日志后(其中包含成千上万的可计数事件),脚本可以读取并更新单个事务中所需的所有内容-可能不直观,但比成千上万个单锁要快得多.

If you need rigorously exact counts but don't need them to be instantly up-to-date, my favorite approach is to append the countable information to a log (switching logs as often as needed for data freshness purposes). Once a log is closed (with thousands of countable events in it), a script can read it and update all that's needed in a single transaction -- maybe not intuitive, but much faster than thousands of single locks.

然后有非常快的计数器,仅统计准确-但由于您不说这种不精确性是可以接受的,因此我不会更深入地解释它们.

Then there's extremely-fast counters that are only statistically accurate -- but since you don't say that such imprecision is acceptable, I'm not going to explain them in more depth.