async function getTokens(userId) {
const lastCleanupTsKey = `user:${userId}:tokens:cleants`
const tokenKey = `user:${userId}:tokens`
cosnt [[lastCleanTimestamp, err1], [size, err2] = await redis.pipeline()
.get(lastCleanupTsKey)
.zcount(tokenKey)
.exec()
if (!lastCleanTimestamp) {
await redis.set(lastCleanupTsKey, <current_timestamp>)
}
if (size !== null && size > CLEANUP_SIZE_THRES_HOLD) { // you can also check if lastCleanup is more than 5 minutes for example here.
await redis.ZREMRANGEBYSCORE(tokenKey, '-inf', <current_timestamp>)
}
// do your logic
}
1条答案
按热度按时间ffdz8vbo1#
您可以使用排序集
key
:user:<id>:tokens
成员名称是token,成员得分是其过期时间戳添加新令牌
zadd <key> <token> <expire_timestamp>
获取用户的所有令牌zrange user:1:tokens 0 -1
. 添加WITHSCORES
如果您需要过期时间戳和令牌。获取具有有效时间的令牌
zrangebyscore <key> <current_ts> +inf
删除所有令牌del <key>
清除代码示例