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

Javascript 在nodeJs的其他模块中使用Redis客户端实例,javascript,node.js,redis,commonjs,Javascript,Node.js,Redis,Commonjs,我有以下连接到Redis数据库的模块,我想获取客户端实例,这样我就可以从其他模块调用它,而无需每次创建新实例,我执行了以下操作: let client; const setClient = ({ redis, config }) => { client = redis.createClient({ host: config.redis.host, port: config.redis.port }); }; const getClient

我有以下连接到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')从其他模块调用客户机时
它给我
未定义的

从顶部(let)擦除letClient(),在底部添加const client=getClient(),在模块导出时只需使用client而不是client: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;

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

在初始化之前无法访问“客户端”。请你提供一个代码片段好吗?