【发布时间】:2019-05-24 15:53:42
【问题描述】:
我曾经使用client.setex(key, 900, value) 来存储单个键值。
但是,我想存储一个有过期时间的对象。
我想出了函数hmset,但是我不知道如何设置过期时间。
我想用它来存储对话中当前聊天的上下文和文本。
请帮忙
【问题讨论】:
标签: node.js redis chat chatbot node-redis
我曾经使用client.setex(key, 900, value) 来存储单个键值。
但是,我想存储一个有过期时间的对象。
我想出了函数hmset,但是我不知道如何设置过期时间。
我想用它来存储对话中当前聊天的上下文和文本。
请帮忙
【问题讨论】:
标签: node.js redis chat chatbot node-redis
要使哈希(或任何其他 Redis 键)过期,请调用 EXPIRE 命令。在你的情况下:
client.hmset(key, ...
client.expire(key, 9000)
【讨论】:
MULTI/EXEC 块或 Lua 脚本来确保原子性,而不是使用专用命令。
由于 hmset 已弃用 (see this),您可以将 hset 与 expire 一起使用 pipeline。
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()
【讨论】:
确保在 key 之后设置过期的好方法是将进程包装在 ES6 异步函数中:
async 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);
}
});
});
}
【讨论】: