【问题标题】:use Redis client instance in other modules in nodeJs在 nodeJs 的其他模块中使用 Redis 客户端实例
【发布时间】:2020-11-26 13:31:22
【问题描述】:

我有以下连接到 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

【问题讨论】:

    标签: javascript node.js redis commonjs


    【解决方案1】:

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

    【讨论】:

    • 初始化前无法访问“客户端”。请问能提供sn-p的代码吗?
    【解决方案2】:

    我想出了以下解决方案:

    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;
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-14
      • 1970-01-01
      • 1970-01-01
      • 2013-04-24
      • 2021-12-23
      • 2022-01-08
      • 2015-02-19
      • 1970-01-01
      相关资源
      最近更新 更多