首页 > 解决方案 > 节点中的 Redis - express。如何在不初始化客户端的情况下扫描密钥

问题描述

我有以下扫描仪

const scan = promisify(redisClient1.scan).bind(redisClient1);

const scanAll = async (pattern) => {
    const found = [];
    let cursor = '0';

    do {
        const reply = await scan(cursor, 'MATCH', pattern);
        cursor = reply[0];
        found.push(...reply[1]);
    } while (cursor !== '0');

    return found;
};

但是要使用它,我每次都必须初始化 redisClient1

const redisClient1 = require('redis').createClient(config.redisPort, config.redisUrl, {
    no_ready_check: true,
    db: 1
});


redisClient1.on('error', function (err) {
    console.log('Error ' + err);
});

redisClient1.on('connect', function () {
    console.log('Connected to Redis pre/dev.');
});

问题是,我需要 scanAll 函数将 redisPort 和 redisUrl 作为参数(db 始终为 1)

所以一旦函数接收到参数,客户端初始化应该发生

这意味着它看起来像这样

const scanAll = async (url, port) => {
        const found = [];
        let cursor = '0';
    
        do {
            const reply = await customScan(url+port;, cursor, 'Match', pattern)            
            cursor = reply[0];
            found.push(...reply[1]);
        } while (cursor !== '0');
    
        return found;
    };

我该怎么做类似的事情?

标签: node.jsnode-redis

解决方案


我结束了这个

const createRedisClient = async (port, url) => {
    const redisClient = require('redis').createClient(config.redisPort, config.redisUrl, {
        no_ready_check: true,
        db: 1
    })
    return redisClient;
}

const scanAll = async (pattern) => {
    const redisClient = await createRedisClient('1111', 'server.com')
    const scan = promisify(redisClient.scan).bind(redisClient);
    const found = [];
    let cursor = '0';
    do {
        const reply = await scan(cursor, 'MATCH', pattern);
        cursor = reply[0];
        found.push(...reply[1]);
    } while (cursor !== '0');
    return found;
};


const serverInfo = async () => {
    const redisClient = await createRedisClient('1111', 'server.com')
    const info = promisify(redisClient.info).bind(redisClient);
    const reply = await info();
    return reply;
}

推荐阅读