python - 如何锁定 AWS S3 上的文件?

标签 python synchronization locking

我所说的锁定并不是指对象锁 S3 可用。我说的是以下情况:

我有多个 (Python) 进程读取和写入 S3 上托管的单个文件;也许该文件是某种需要定期更新的索引。

这些进程并行运行,因此我想确保在给定时间只有一个进程可以写入文件(以避免同时写入破坏数据)。

如果我将其写入共享文件系统,我可以只要求使用 flock 并将其用作同步文件访问的方式,但我无法在 S3 上执行此操作。

在 AWS S3 上锁定文件的最简单方法是什么?

最佳答案

不幸的是,AWS S3 不提供锁定对象的 native 方式 - 正如您所指出的,没有 flock 类似物。相反,您有几个选择:

使用数据库

例如,Postgres 提供 advisory locks 。设置此功能时,您需要执行以下操作:

  1. 确保所有进程都可以访问数据库。
  2. 确保数据库可以处理传入连接(如果您正在运行某种类型的大型处理网格,那么您可能需要将 Postgres 实例放在 PGBouncer 后面)
  3. 请注意,在完成锁定之前,不要从客户端关闭 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/

相关文章:

c - Pthread 条件信号 - 未按预期工作

javascript - 功能增量与视频同步(或自动增量)

emacs - 有什么方法可以在 Redmine(或其他问题跟踪器)和纯文本待办事项列表之间进行同步?

python - 在 spaCy 管道中对自定义组件进行基准测试的最佳方法是什么?

python - 您如何为加权平均平均值迭代地为数据框列赋予权重?

java - 如果我从 synchronized block 返回,什么时候释放锁?

synchronization - MIPS 与锁同步

java - Guava Striped 的正确条纹数是多少?

python - 如何获取在 sklearn.cross_validation.cross_val_score 中内部分区的折叠本身?

Python二叉树实现插入方法: help required