在Python中可以WATCH多个Redis键吗?

5 投票
1 回答
3656 浏览
提问于 2025-04-17 19:38

最近我在玩Redis,想知道怎么一次监视多个键。像下面这样的操作算不算原子操作呢?

以下代码使用的是redis-py库:

 while True:            
        try:
            pipe.watch(key)
            pipe.watch(another_key)
            pipe.multi()
            pipe.set(key, value)
            pipe.set(another_key, another_value)
            pipe.execute()

            break
        except redis.WatchError:
            continue

        finally:
            pipe.reset()

1 个回答

7

Redis确实支持多个键,没错:http://redis.io/commands/watch

虽然Python客户端的文档说管道命令是原子执行的,但我还是建议用一个WATCH调用,传入多个参数:

pipe.watch(key, another_key)

撰写回答