在nodejs的其他模块中使用redis客户端示例

js4nwp54  于 2021-06-09  发布在  Redis
关注(0)|答案(2)|浏览(477)

我有一个连接到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

z3yyvxxp

z3yyvxxp1#

从顶部(let)删除letclient(),在底部添加const client=getclient(),在模块导出时只使用client而不是client:getclient()

c7rzv4ha

c7rzv4ha2#

我提出了以下解决方案:

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;

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

相关问题