使用 memcached 和 MySQL 等 RDBMS 时的缓存一致性
这学期我选修了数据库课程,我们正在学习如何维护 RDBMS 和缓存服务器(例如 memcached)之间的缓存一致性。当存在竞争条件时,就会出现一致性问题。例如:
- 假设我从缓存中执行 get(key) 操作,并且存在缓存未命中。因为缓存未命中,所以我从数据库中获取数据,然后将
put(key,value)
放入缓存中。 - 但是,可能会发生竞争条件,其他用户可能会删除我从数据库中获取的数据。此删除可能会在我将
放入
放入缓存之前发生。
因此,理想情况下不应将数据放入缓存,因为数据在数据库中存在的时间较长。
如果缓存条目具有 TTL,则缓存中的条目可能会过期。但仍然存在缓存中数据与数据库不一致的窗口。
我一直在寻找谈论此类问题的文章/研究论文。但是,我找不到任何有用的资源。
I have taken a database class this semester and we are studying about maintaining cache consistency between the RDBMS and a cache server such as memcached. The consistency issues arise when there are race conditions. For example:
- Suppose I do a
get(key)
from the cache and there is a cache miss. Because I get a cache miss, I fetch the data from the database, and then do aput(key,value)
into the cache. - But, a race condition might happen, where some other user might delete the data I fetched from the database. This delete might happen before I do a
put
into the cache.
Thus, ideally the put
into the cache should not happen, since the data is longer present in the database.
If the cache entry has a TTL, the entry in the cache might expire. But still, there is a window where the data in the cache is inconsistent with the database.
I have been searching for articles/research papers which speak about this kind of issues. But, I could not find any useful resources.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
本文为您提供了有关 Facebook 如何(尝试)维护缓存一致性的有趣说明:http://www.25hoursaday.com/weblog/2008/08/21/HowFacebookKeepsMemcachedConsistentAcrossGeoDistributedDataCenters.aspx
以下是本文的要点。
This article gives you an interesting note on how Facebook (tries to) maintain cache consistency : http://www.25hoursaday.com/weblog/2008/08/21/HowFacebookKeepsMemcachedConsistentAcrossGeoDistributedDataCenters.aspx
Here's a gist from the article.
使用内存缓存中保存的变量作为锁定信号怎么样?
从数据库检索数据后,每个内存缓存命令都是原子的
,将数据放入内存缓存后打开锁定
关闭锁定,检查锁定状态
,从数据库删除之前
How about using a variable save in memcache as a lock signal?
every single memcache command is atomic
after you retrieved data from db, toggle lock on
after you put data to memcache, toggle lock off
before delete from db, check lock state
下面的代码展示了如何使用Memcached的
add
、gets
和cas
操作来实现乐观锁,以保证缓存与数据库的一致性.免责声明:我不保证它完全正确并处理所有竞争条件。此外,一致性要求可能因应用程序而异。
The code below gives some idea of how to use Memcached's operations
add
,gets
andcas
to implement optimistic locking to ensure consistency of cache with the database.Disclaimer: i do not guarantee that it's perfectly correct and handles all race conditions. Also consistency requirements may vary between applications.
当您阅读时,会发生以下情况:
当您写入时,会发生以下情况:
When you read, the following happens:
When you write, the following happens: