我所说的锁定并不是指对象锁 S3 可用。我说的是以下情况:
我有多个 (Python) 进程读取和写入 S3 上托管的单个文件;也许该文件是某种需要定期更新的索引。
这些进程并行运行,因此我想确保在给定时间只有一个进程可以写入文件(以避免同时写入破坏数据)。
如果我将其写入共享文件系统,我可以只要求使用 flock
并将其用作同步文件访问的方式,但我无法在 S3 上执行此操作。
在 AWS S3 上锁定文件的最简单方法是什么?
最佳答案
不幸的是,AWS S3 不提供锁定对象的 native 方式 - 正如您所指出的,没有 flock
类似物。相反,您有几个选择:
使用数据库
例如,Postgres 提供 advisory locks 。设置此功能时,您需要执行以下操作:
- 确保所有进程都可以访问数据库。
- 确保数据库可以处理传入连接(如果您正在运行某种类型的大型处理网格,那么您可能需要将 Postgres 实例放在 PGBouncer 后面)
- 请注意,在完成锁定之前,不要从客户端关闭 session 。
使用咨询锁时还需要考虑其他一些注意事项 - 来自 Postgres 文档:
Both advisory locks and regular locks are stored in a shared memory pool whose size is defined by the configuration variables max_locks_per_transaction and max_connections. Care must be taken not to exhaust this memory or the server will be unable to grant any locks at all. This imposes an upper limit on the number of advisory locks grantable by the server, typically in the tens to hundreds of thousands depending on how the server is configured.
In certain cases using advisory locking methods, especially in queries involving explicit ordering and LIMIT clauses, care must be taken to control the locks acquired because of the order in which SQL expressions are evaluated
使用外部服务
我见过人们使用类似 lockable 的东西来解决这个问题。来自他们的docs ,他们似乎有一个 Python 库:
$ pip install lockable-dev
from lockable import Lock
with Lock('my-lock-name'):
#do stuff
如果您不使用 Python,您仍然可以通过访问某些 HTTP 端点来使用他们的服务:
curl https://api.lockable.dev/v1/acquire/my-lock-name
curl https://api.lockable.dev/v1/release/my-lock-name
关于python - 如何锁定 AWS S3 上的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72632893/