我有一些格式的Redis有很多键,我想获得匹配某些模式的键并对它们进行一些操作.我不使用KEYS方法,因为它不建议在生产中使用.使用SCAN我想知道在代码中编写它的最佳方法是什么.我必须
'use strict' const Promise = require('bluebird'); const config = require('./config'); const client = require('./clinet'); let iterator = 0; Promise.coroutine(function* () { do { iterator = yield clinet.scanAsync(iterator, 'myQuery', 'COUNT', config.scanChunkSize) .then(data => { let nextIterator = data[0]; let values = data[1]; //do some magic with values return nextIterator; }) } while (iterator !== '0'); })();
有没有更好的方法来做到我错过了?
您可以使用递归来保持调用扫描直到完成.function scanAsync(cursor, pattern, returnSet){ return redisClient.scanAsync(cursor, "MATCH", pattern, "COUNT", "100").then( function (reply) { cursor = reply[0]; var keys = reply[1]; keys.forEach(function(key,i){ returnSet.add(key); }); if( cursor === '0' ){ return Array.from(returnSet); }else{ return scanAsync(cursor, pattern, returnSet) } }); }
传入Set()以确保密钥不重复
myResults = new Set(); scanAsync('0', "NOC-*[^listen]*", myResults).map( function( myResults ){ console.log( myResults); } );