ioredis按模式

时间:2016-03-13 09:17:01

标签: node.js redis

我正在使用ioredis with express(nodejs) 我知道有一种方法可以按照这样的模式删除键:

redis-cli KEYS "sample_pattern:*" | xargs redis-cli DEL

但是,有没有办法使用ioredis呢?

3 个答案:

答案 0 :(得分:18)

按模式删除密钥的最简单方法是使用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

答案 1 :(得分:0)

我对ioredis不太了解。 但我认为键*和for循环可以处理它。

顺便说一句,我建议您使用scan和del而不是

答案 2 :(得分:0)

尝试以下命令,您可以为每个前缀创建多个客户端,支持set get和clear:

// 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");