// 用scan方式,遍历redis中的所有key
var redis = require('redis');
var client = redis.createClient({
host: '127.0.0.1',
port: 6379,
db: 0
});
var g_iRoundNo = 0;
var g_iMilliSecond = 200;
client.on('error', function(err) {
console.log('Error: ' + err);
});
function my_redis_scan_keys(cursor, pattern, allKeys) {
g_iRoundNo ++;
console.log('RoundNo.', g_iRoundNo, 'starting...');
if (!allKeys) {
allKeys = [];
}
client.scan(cursor, 'MATCH', pattern, 'COUNT', 100000, function(err, result) {
if (err) {
throw err;
}
var keys = result[1];
var nextCursor = result[0];
allKeys = allKeys.concat(keys);
if (nextCursor !== '0') {
// 继续遍历
console.log('RoundNo.', g_iRoundNo, 'OK');
setTimeout(function() {
my_redis_scan_keys(nextCursor, pattern, allKeys);
}, g_iMilliSecond);
} else {
// 遍历完成
console.log('RoundNo.', g_iRoundNo, 'OK -- full completed');
console.log('allKeys.length:', allKeys.length);
process.exit(0);
}
});
}
console.log('before');
my_redis_scan_keys('0', '11*');
console.log('after');