您无法使用管道实现这一目标,因为直到执行完整个管道后,您才知道密钥是否存在。相反,您可以使用Lua脚本来完成这项工作:
local key = KEYS[1]local field = ARGV[1]local value = ARGV[2]local ttl = ARGV[3]local exist = redis.call('exists', key)redis.call('hset', key, field, value)if exist == 0 then redis.call('expire', key, ttl)end选中此项以查看如何使用redis-
py运行Lua脚本。然后使用管道运行脚本以减少
RTT。
更新
如果您坚持使用
WATCH来完成这项工作,则可以尝试以下代码:
with r.pipeline() as pipe: while 1: try: pipe.watch(hkey) exist = pipe.exists(hkey) pipe.multi() if not exist: pipe.hset(hkey, v, v) pipe.expire(hkey, 3600) else: pipe.hset(hkey, v, v) pipe.execute() break; except WatchError: continue



