AWS RDS 数据库无法读取刚刚写入数据库的记录

AWS RDS database can't read record that was just written to database

我看到一些使用 AWS RDS 数据库的 Laravel 代码出错。该代码将一条记录写入数据库,然后立即使用主键进行搜索以加载该记录,但没有得到任何结果。

如果我之后手动尝试,我会找到记录。如果我在代码中插入 1 秒睡眠,它会正常工作。

我已经尝试使用 Laravel 的读取和写入主机的单独设置。我也试过将它们设置为同一台主机并且只使用一台主机。结果总是一样的。但是其他相同配置的环境没有这个错误。

RDS 中是否有一个选项需要更改才能使记录在写入后立即可用。

错误是由于 mySQL master-slave replication lag

A common mistake is to use a mySQL cluster and then perform a read immediately after a write.

由于读取发生在其中一台 slave/read 主机上,而写入发生在主机上,因此读取时不会复制数据。

有几种方法可以纠正错误:

  1. 紧接着的读取必须在主机(而不是从机)上执行。即使您已经提到您将其更改为单个主机,但人们在切换连接时经常会犯错误。请参考此 以正确切换 Laravel
  2. 中的连接
  3. 一个更简单的方法可能是使用 sticky 数据库 option in Laravel. Beware: this may cause performance issues 如果不小心仅用于您想要的用例。来自文档:

The sticky option is an optional value that can be used to allow the immediate reading of records that have been written to the database during the current request cycle. If the sticky option is enabled and a "write" operation has been performed against the database during the current request cycle, any further "read" operations will use the "write" connection.

  1. 最 "non-obvious" 的方法是不要在写入后立即执行读取。根据您的用例考虑是否可以避免这种情况。

  2. 其他方法:参考这个SO post