最近项目里需要将原来的一批数据,重新赋值。但同时也得设置好过期时间。为了减少网络的开销,第一想法就是使用MSET的命令。 然而使用该命令,会将key的过期时间直接设置成永久,显然,不能直接这么用。

为什么官方没有提供相关的API

1
Unfortunately, we're not going to add more commands that can work on multiple keys because they are inherently difficult to distribute. Instead, explicitly calling EXPIRE for every key you want to expire is much easier to distribute (you can route every command to a different server if needed). If you want to EXPIRE keys atomically, you can wrap multiple calls in a MULTI/EXEC block.

根据官方人员的回复,类似批量设置过期时间的主要难点,是在于分布式集群的环境下,如果MSET对应不同的集群的slot,那么就不太容易处理。所以像mset的操作,在事先不清楚每个key所在的slot的情况下,是不推荐使用的。 同理,批量的设置key的过期时间亦是如此。

怎么解决

并没有特别好的解决方案, 如果需要对批量的用户进行设置值并设置过期时间

1
2
3
SET key value expire
SET key1 value1 expire
SET key2 value2 expire

我们可以多次使用set命令。

如果是单节点非集群,觉得多次的set命令对网络消耗过大,那我们可以使用pipeline的方式,一次性提交所有的命令。

参考文献