在 nodeJs 的其他模块中使用 Redis 客户端实例

use Redis client instance in other modules in nodeJs

我有以下连接到 Redis 数据库的模块,我想获取客户端实例以便我可以从其他模块调用它而无需每次都创建新实例,我执行了以下操作:

let client;

const setClient = ({ redis, config }) => {
    client = redis.createClient({
        host: config.redis.host,
        port: config.redis.port
    });
};

const getClient = () => {
    return client;
};

const connect = ({ redis, config, logger }) => {
    setClient({ redis, config });
    client.on('connect', () => {
        logger.info(`Redis connected on port: ${client?.options?.port}`);
    });
    client.on('error', err => {
        logger.error(`500 - Could not connect to Redis: ${err}`);
    });
};

module.exports = { connect, client: getClient() };

当我使用 const { client } = require('./cache'); 从其他模块调用客户端时,它给我 undefined

从顶部(let)删除 letClient() 并在底部添加 const client = getClient() 并在模块导出时使用客户端而不是客户端:getClient()

我想出了以下解决方案:

const cacheClient = () => {
    return {
        client: undefined,
        setClient({ redis, config }) {
            client = redis.createClient({
                host: config.redis.host,
                port: config.redis.port
            });
        },

        getClient() {
            return client;
        },

        connect({ redis, config, logger }) {
            this.setClient({ redis, config });
            client.on('connect', () => {
                logger.info(`Redis connected on port: ${client?.options?.port}`);
            });
            client.on('error', err => {
                logger.error(`500 - Could not connect to Redis: ${err}`);
            });
        }
    };
};

module.exports = cacheClient;

如果有更好的方法请告诉我。