如何在redis上同步多个编写器?

Lor*_*lli 5 synchronization redis

我有多个作者覆盖了 redis 中的同一个键。我如何保证只有被选中的人写最后?

我可以在 Redis 中执行写同步而不先同步编写器吗?


背景:在我的系统中,一个独特的调度员将工作发送给不同的工人。然后每个工作人员将结果写入 Redis 并覆盖相同的键。我需要确保只有从调度程序接收工作的最后一个工人在 Redis 中写入。 

Lor*_*lli 4

使用有序集 ( ZSET ):添加分数等于 unix 时间戳的条目,然后删除除最高排名之外的所有条目。

\n\n

Redis有序集是一个集合,其中每个条目也有一个分数。集合按照分数进行排序,元素在有序集合中的位置称为Rank。

\n\n

为了:

\n\n
    \n
  1. 删除分数等于或小于您添加的分数的所有条目 ( zremrangebyscore )。由于您要添加到一个集合中,如果您的值重复,您的新条目将被忽略,您希望保留具有最高排名的条目。\xc2\xa0
  2. \n
  3. 将您的值添加到 zset ( zadd )
  4. \n
  5. 按排名删除所有条目,但排名最高的条目除外 ( zremrangebyrank )
  6. \n
  7. 您应该在事务(管道)内执行此操作
  8. \n
\n\n

python 中的示例:

\n\n
# timestamp contains the time when the dispatcher sent a message to this worker\nkey = "key_zset:%s"%id\npipeline = self._redis_connection.db.pipeline(transaction=True)\npipeline.zremrangebyscore(key, 0, t) \xc2\xa0# Avoid duplicate Scores and identical data\npipeline.zadd(key, t, "value")\npipeline.zremrangebyrank(key, 0, -2)\npipeline.execute(raise_on_error=True)\n
Run Code Online (Sandbox Code Playgroud)\n