如何正确处理 GAE 数据存储中的计数器更新?
假设我的数据存储中有页面浏览量计数器。 为了在每个页面显示时增加其值,我需要读取该值,增加该值并增加。我如何确保当 2 个(或更多)用户查看该页面时,两个视图都会被计数(即,在更新 user1 的计数器值之前,不会出现 user2 的计数器值被读取的情况)?
Let's say I have page views counter in my datastore.
In order to increase its value with each page display, I need to read the value, increment that and increase. How can I be sure that in case when 2 (or more) users view the page, both views are counted (i.e. there will not be a case that for user2 we read the counter value before we've updated that for user1)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于此类情况,您需要使用分片计数器。
You'll want to use Sharded Counters for such cases.
作为精确值不如性能重要的分片计数器的替代方案,请考虑使用 后写式计数器。或者,使用 Google Analytics 之类的工具,而不是尝试自己计算页面浏览量。
As an alternative to sharded counters where exact values are less important than performance, consider using write-behind counters. Alternately, use something like Google Analytics, rather than trying to count pageviews yourself.