如何持续增加计数器缓存列? [英] How do I consistently increase a counter cache column?

查看:112
本文介绍了如何持续增加计数器缓存列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个计数器缓存,需要在每次页面加载时递增.假设我有 10 个 Web 实例.如何持续增加计数器缓存列?

Lets say I have a counter cache that needs to to be incremented on every page load. Say I have 10 web instances. How do I consistently increase a counter cache column?

使用一个 Web 实例即可轻松实现一致性.但是在运行多个实例时,可能会出现竞争条件.

Consistency is easy with one web instance. but with several instances running, A race conditions may occur.

这里有一个简单的解释.假设我的计数器缓存列名为 foo_counts,其起始值为 0.如果同时加载 2 个 Web 实例,则两者都实现计数为 0.到了增加计数的时候.它们都将计数从 0 增加到 1.

Here is a quick explanation. Let's say my counter cache column is called foo_counts and its starting value is 0. If 2 web instance are loaded at the same time, both realize the count as 0. When it comes time to increase the count. They both increment the count from 0 to 1.

我查看了 http://guides.rubyonrails.org/active_record_querying.html#locking-records-for-update

任何想法将不胜感激.

推荐答案

你可以使用 update_counter:

You could use update_counter:

increment_counter(counter_name, id)

将数字字段加一,通常表示一个计数.

Increment a number field by one, usually representing a count.

这会在 SQL 中进行直接更新,因此 Model.increment_counter(:c, 11) 将此 SQL 发送到数据库:

This does a direct UPDATE in SQL so Model.increment_counter(:c, 11) sends this SQL to the database:

update models set c = coalesce(c, 0) + 1 where id = 11

所以你不必担心竞争条件.让数据库完成它的工作.

so you don't have to worry about race conditions. Let the database do its job.

这篇关于如何持续增加计数器缓存列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆