栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何根据密钥的存在情况在Redis中设置哈希密钥过期

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何根据密钥的存在情况在Redis中设置哈希密钥过期

您无法使用管道实现这一目标,因为直到执行完整个管道后,您才知道密钥是否存在。相反,您可以使用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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/379370.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号