如何在不影响剩余 TTL 的情况下更新 redis 值? [英] How can I update a redis value without affecting the remaining TTL?

查看:79
本文介绍了如何在不影响剩余 TTL 的情况下更新 redis 值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在不删除现有 ttl 的情况下 SET redis 键?目前我知道的唯一方法是找出 ttl 并执行 SETEX 但这似乎不太准确.

Is it possible to SET redis keys without removing their existing ttl? The only way I know of at the present time is to find out the ttl and do a SETEX but that seems less accurate.

推荐答案

根据 Redis 文档SET 命令删除 TTL,因为密钥被覆盖了.

According to Redis documentation, the SET command removes the TTL because the key is overwritten.

但是,您可以使用 EVAL 命令来评估 Lua 脚本以自动为您执行.

However you can use the EVAL command to evaluate a Lua script to do it automatically for you.

下面的脚本会检查一个键的 TTL 值,如果该值为正,它会使用新值和剩余的 TTL 调用 SETEX.

The script bellow checks for the TTL value of a key, if the value is positive it calls SETEX with the new value and using the remaining TTL.

local ttl = redis.call('ttl', ARGV[1]) 如果 ttl >0 然后返回 redis.call('SETEX', ARGV[1], ttl, ARGV[2]) end

local ttl = redis.call('ttl', ARGV[1]) if ttl > 0 then return redis.call('SETEX', ARGV[1], ttl, ARGV[2]) end

示例:

>设置键 123

好的

>过期密钥 120

(整数)1

...几秒钟后

>ttl键

(整数)97

>eval "local ttl = redis.call('ttl', ARGV[1]) 如果 ttl >0 然后返回 redis.call('SETEX', ARGV[1], ttl, ARGV[2]) end";0 键 987

> eval "local ttl = redis.call('ttl', ARGV[1]) if ttl > 0 then return redis.call('SETEX', ARGV[1], ttl, ARGV[2]) end" 0 key 987

好的

>ttl键

96

>获取密钥

987"

这篇关于如何在不影响剩余 TTL 的情况下更新 redis 值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆