带有事务的 Memcache?

发布于 2024-10-20 05:20:32 字数 410 浏览 2 评论 0原文

虽然我找不到任何东西,但我想我应该仔细检查 - memcache 是否支持事务?

如果不是,我打赌这就是可能的答案,那么在有事务的环境中使用内存缓存的正确方法是什么?是否每次计划更新时都必须从数据库中读取数据,即使数据位于缓存中,这样您就可以设置锁?例如,更新某些数据的脚本如下所示:

  1. BEGIN;选择...进行更新;
  2. 计算...
  3. 更新表...;
  4. 更新缓存
  5. 提交;

我认为您必须在运行更新查询后更新缓存,以防遇到死锁并需要回滚。但是您还应该在提交之前更新缓存,以防任何其他线程正在等待读取您的数据,并且可能会意外地使用您之前的更新数据更新其缓存,从而导致现在过时的数据覆盖它。

这是正确的步骤顺序吗?有什么方法可以不必在读取更新时访问数据库?

Although I couldn't find anything on it, I thought I would double check - does memcache support transactions?

If not, which I'm betting is the likely answer, then what is the correct method to work with memcache in an environment with transactions? Wouldn't you have to read from the DB every time you plan to update, even if the data is in cache, just so you can set your locks? For example, a script that updates some data would look like this:

  1. BEGIN; SELECT ... FOR UPDATE;
  2. Calculate...
  3. UPDATE TABLE ...;
  4. Update cache
  5. COMMIT;

I think you have to update cache after you run your update query, in case you hit a deadlock and need to rollback. But you should also update cache before committing, in case any other thread is waiting to read your data and may accidentally update it's cache with even newer data before you, resulting in your now-out-of-date data overwriting it.

Is this the correct sequence of steps? Is there any way to not have to hit the db on reads for update?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

尤怨 2024-10-27 05:20:32

Memcache 确实有一个名为 CAS(检查并设置 - 或比较并交换)的运算符,它可能会对您有所帮助。 PHP手册有一些关于它的文档,Memcached::cas,但它应该其他库和语言也支持。

Memcache does have an operator called CAS (Check And Set - or Compare And Swap) which may help you. The PHP manual has some documentation on it, Memcached::cas, but it should also be supported in other libraries and languages.

淡看悲欢离合 2024-10-27 05:20:32

Memcached 不支持这个意义上的事务,尽管它的操作是原子的。您可以使用数据库事务机制并手动更新缓存(按照您的指定),或者使用事务包装器,例如 this。

Memcached does not support transactions in this sense, although its operations are atomic. You can use your database transactioning mechanism and update cache manually (as you specified), or use transactioned wrapper like this.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文