【发布时间】: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