如何在不影响剩余TTL的情况下更新redis值?

pau*_*kon 10 redis node-redis

是否可以在SET不删除现有ttl的情况下重新启动密钥?我目前唯一知道的方法是找出ttl并做一个SETEX但看起来不那么准确.

小智 16

KEEPTTL选项将被添加到SET在redis的> = 6.0

https://redis.io/commands/set

https://github.com/antirez/redis/pull/6679

The SET command supports a set of options that modify its behavior:

EX seconds -- Set the specified expire time, in seconds.
PX milliseconds -- Set the specified expire time, in milliseconds.
NX -- Only set the key if it does not already exist.
XX -- Only set the key if it already exist.
(!) KEEPTTL -- Retain the time to live associated with the key.
Run Code Online (Sandbox Code Playgroud)


小智 12

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

但是,您可以使用该EVAL命令评估Lua脚本以自动执行此操作.

下面的脚本检查密钥的TTL值,如果值为正,则SETEX使用新值并使用剩余的TTL 调用.

local ttl = redis.call('ttl',ARGV [1])如果ttl> 0则返回redis.call('SETEX',ARGV [1],ttl,ARGV [2])结束

例:

>设置键123

>到期密钥120

(整数)1

......过了几秒钟

> ttl键

(整数)97

> eval"local ttl = redis.call('ttl',ARGV [1])如果ttl> 0则返回redis.call('SETEX',ARGV [1],ttl,ARGV [2])结束"0键987

> ttl键

96

>得到钥匙

"987"


Kri*_*czi 6

也许INCR,INCRBY,DECR等可以帮助你.他们不修改TTL.

> setex test 3600 13
OK

> incr test
(integer) 14

> ttl test
(integer) 3554
Run Code Online (Sandbox Code Playgroud)

http://redis.io/commands/INCR