在节点中使用Redis SCAN [英] Using Redis SCAN in NODE
问题描述
我的 Redis 有很多某种格式的键,我想获得匹配某种模式的键并对它们进行一些操作.我不使用 KEYS 方法,因为它不推荐在生产中使用.使用 SCAN 我想知道用代码编写它的最佳方法是什么.我必须做一些类似 while 循环的事情,但是使用 promises,我当前的解决方案看起来像这样(代码稍微简化了一点):
I have Redis with a lot of keys in some format and I want to get keys that match some pattern and do some operations on them. I don't use KEYS method since it's not recommend in production. Using SCAN I'm wondering what is the best way to write it in code. I have to do something like a while loop but using promises, my current solution looks like this (code is simplified a little):
'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');
})();
有没有更好的方法来实现我所缺少的?
Is there a better way to do it that I'm missing?
推荐答案
您可以使用递归来保持调用 scan 直到完成.
You can use recursion to keep calling scan until done.
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() 以确保键不会重复
Pass in a Set() to make sure keys aren't duplicated
myResults = new Set();
scanAsync('0', "NOC-*[^listen]*", myResults).map(
function( myResults ){ console.log( myResults); }
);
这篇关于在节点中使用Redis SCAN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!