19

redis 如何实现 [每次访问 key 后自动延长 key 的过期时间]

 2 years ago
source link: https://www.v2ex.com/t/802679
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

V2EX  ›  程序员

redis 如何实现 [每次访问 key 后自动延长 key 的过期时间]

  Aliberter · 4 小时 50 分钟前 · 1123 次点击

大佬们 redis 自身有这个实现吗?还是说要自己实现?我用 springboot-redis 的 redisTemplate 的。谢谢!

6 条回复    2021-09-18 10:27:17 +08:00

Saxton   4 小时 47 分钟前

给这个 key 重新 set 一下时间不就重置了

Aliberter   4 小时 44 分钟前

@Saxton 嗯..对..只是怕自己不了解,万一自身就有这种实现,问一下

Cloud9527   4 小时 40 分钟前

这种问题直接看官方文档最快,不过 1 楼的方法是对的

rationa1cuzz   4 小时 28 分钟前

加时间貌似每次要先读 ttl 时间,再重新 set,多了一步操作,如果延长过期时间没有限制,1 楼感觉就挺好的。

PiersSoCool   3 小时 51 分钟前

写个 Lua 脚本最好,原子操作

Pipecraft   3 小时 39 分钟前   1

redis 6.2.0 版本新加的 GETEX 就是这个功能,[每次访问 key 后自动延长 key 的过期时间]。
具体看官方文档。redis.io/commands/getex

如果是老版本,不需要用 SET 命令重置时间,用 EXPIRE, EXPIREAT, PEXPIRE 或 PEXPIREAT 会更好些。

如果你的过期时间比较长,访问同一个 key 的频率很高(作为缓存,这个可能性很高),那么每次 GET 一次然后又 EXPIRE 一次,这样调用两次命令有点浪费。可以考虑异步更新过期时间。比如把要更新的 key 先存到内存里,定时更新一次。这样多次 GET,一定时间内只更新一次就可以了。当然这个方法会增加复杂性。性能和复杂性权衡一下,选择用简单的 GET + EXPIRE 方式还是异步方式。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK