我以前使用client.setex(key, 900, value)
来存储单个键值对。
但是,我想要存储一个带有过期时间的对象。
我想到了hmset
函数,但是我不知道如何设置过期时间。
我想将其用于在对话中存储当前聊天的内容和文本。
请帮忙。
我以前使用client.setex(key, 900, value)
来存储单个键值对。
但是,我想要存储一个带有过期时间的对象。
我想到了hmset
函数,但是我不知道如何设置过期时间。
我想将其用于在对话中存储当前聊天的内容和文本。
请帮忙。
要过期一个哈希(或任何其他Redis键),请调用EXPIRE
命令。在您的情况下:
client.hmset(key, ...
client.expire(key, 9000)
由于hmset
已被弃用(请参考此链接),您可以使用pipeline
和hset
来设置expire
。
pipe = client.pipeline()
pipe.hset(key, mapping=your_object).expire(duration_in_sec).execute()
# for example:
pipe.hset(key, mapping={'a': 1, 'b': 2}).expire(900).execute()
注意:管道操作并不保证原子性。
multi()
而不是pipeline()
(正如您链接的文章中所述)。 - undefinedasync function (keyString, token, ttl) {
return new Promise(function(resolve, reject) {
redisClient.hmset("auth", keyString, token, function(error,result) {
if (error) {
reject(error);
} else {
redisClient.expire(keyString, ttl)
resolve(result);
}
});
});
}
MULTI/EXEC
块或 Lua 脚本来确保原子性,代替专用命令。 - Itamar Haber