2016-03-13 4 views

ответ

0

Я не очень люблю ioredis. Но я думаю, что клавиши * и для цикла могут справиться с этим.

Btw, я полагаю, что вы должны использовать сканирование и дель вместо ~

13

Самый простой способ удалить ключи от шаблона используется keys команду, чтобы получить ключи, соответствующие шаблону, а затем удалить их один за другим, что аналогичен приведенному вами примеру командной строки. Вот пример реализован с ioredis:

var Redis = require('ioredis'); 
var redis = new Redis(); 
redis.keys('sample_pattern:*').then(function (keys) { 
    // Use pipeline instead of sending 
    // one command each time to improve the 
    // performance. 
    var pipeline = redis.pipeline(); 
    keys.forEach(function (key) { 
    pipeline.del(key); 
    }); 
    return pipeline.exec(); 
}); 

Однако, когда база данных имеет большой набор ключей (скажем, миллион), keys будет блокировать базу данных в течение нескольких секунд. В этом случае полезно использовать scan. ioredis имеет scanStream функцию, чтобы помочь вам перебрать базу данных легко:

var Redis = require('ioredis'); 
var redis = new Redis(); 
// Create a readable stream (object mode) 
var stream = redis.scanStream({ 
    match: 'sample_pattern:*' 
}); 
stream.on('data', function (keys) { 
    // `keys` is an array of strings representing key names 
    if (keys.length) { 
    var pipeline = redis.pipeline(); 
    keys.forEach(function (key) { 
     pipeline.del(key); 
    }); 
    pipeline.exec(); 
    } 
}); 
stream.on('end', function() { 
    console.log('done'); 
}); 

Не забудьте проверить официальную документацию scan команды для получения дополнительной информации: http://redis.io/commands/scan.

+0

Я думаю, с помощью 'unlink' более эффективен, чем 'del', например,' redis.unlink (keys) 'и удалять цикл' конвейер' и 'forEach'. –

0

попробовать следующие команды, где вы можете создать несколько клиентов для каждого префикса, которые поддерживают набор получают и ясно:

// myredis.js 
const Redis = require('ioredis'); 
const ConnectRedis = require('connect-redis'); 
const config = {}; // your ioredis config 
const clients = {}; 

/** 
* @private create redis client 
* @param {string} name client name 
* @param {boolean} isSession is this the application session client or not 
* @return {Redis|*} 
*/ 
const createClient = (name, isSession = false) => { 
    let client; 
    client = new Redis({...config, "keyPrefix":`${name}:`)}); 
    client.on('error', msg => console.log("Redis Client[" + name + "]: " + msg)); 
    client.on('connect',() => console.log("Redis Client[" + name + "]: Connected")); 
    if (isSession) { 
    const RedisStore = ConnectRedis(isSession); 
    client = new RedisStore({client}); 
    } 
    return client; 
}; 

/** 
* Create or get redis client 
* @param {string} name client name 
* @return {Redis|*} 
*/ 
const getClient = name => { 
    let client = clients[name]; 
    if (!client || !client.connected) { 
    client = clients[name] = createClient(name); 
    } 
    return client; 
}; 

/** 
* get keys only related to this client prefix 
* @param name 
*/ 
const getClientKeys = name => getClient(name).keys(`${name}:*`).then(keys => keys.map(key => key.substr(name.length + 1))); 

/** 
* clear client 
* @param name 
*/ 
const clearClient = name => getClientKeys(name).then(keys => { 
    const client = getClient(name); 
    client && keys.forEach(key => client.del(key)) 
}); 

module.exports = {getClient, clearClient, getClientKeys}; 

Как использовать:

const {getClient, clearClient} = require("./myredis"); 
// this will get a client with prefix "marvel:" and if it is not exists it will be created 
const client = getClient("marvel"); 

// set value 
client.set("fav", "ironman"); 

// get the value 
client.get("fav", (error, value) => console.log(value)); 

// clear client 
clearClient("marvel"); 
Смежные вопросы