我正在使用带有redis
npm软件包的Node.JS脚本来检索与模式animals:toFeed:*
匹配的所有Redis密钥。匹配项的示例为键animals:toFeed:17ed160f59c5b31caf7e741a4e62cb7785414cd
。
使用下面的代码,可以有10个匹配项,但是代码只会返回一些匹配项,例如2-3。可能是什么问题,我们该如何解决?
使用Redis 4.0.11,Node.js 8.11.3,redis 2.8.0 npm软件包
async function scanAsync(cursor, pattern, results) {
return redis.scanAsync(cursor, 'MATCH', pattern, 'COUNT', '10')
.then(function(reply) {
cursor = reply[0]
if(cursor === '0') {
console.log('Scan complete')
} else {
console.log('Match #', i)
let keys = reply[1]
keys.forEach(function(key, i) {
results.push(key)
})
return scanAsync(cursor, pattern, results)
}
})
}
let keys = []
let prefix = 'animals:toFeed:*'
await scanAsync('0', prefix, keys)
答案 0 :(得分:2)
当光标等于results
时,您忘记将键添加到'0'
中了,但是您应该始终添加这些键。
您可以考虑以下代码:
async function scanAsync(cursor, pattern, results) {
return redis.scanAsync(cursor, 'MATCH', pattern, 'COUNT', '10')
.then(function(reply) {
let keys = reply[1]
keys.forEach(function(key) {
results.push(key)
})
cursor = reply[0]
if(cursor === '0') {
console.log('Scan complete')
} else {
return scanAsync(cursor, pattern, results)
}
})
}
答案 1 :(得分:0)
…或您使用redis-async-gen,这使您不必自己仔细控制所有这些。 (详细了解here。)
const redis = require('redis')
const client = redis.createClient(…)
const generators = require('redis-async-gen')
const { keysMatching } = generators.using(client)
const results = []
for await (const key of keysMatching('test*')) {
results.push(key)
}