[英]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() 並在模塊導出僅 go 與客戶端而不是客戶端: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;
如果有更好的方法請告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.