我想在我的Express应用程序启动时仅连接一次Redis客户端,但我不想使用global
。
我该怎么办?
谢谢
答案 0 :(得分:1)
您可以使用Singleton类初始化Redis并建立与Redis的连接。
例如:-
var redis = require('redis');
class Redis {
constructor() {
this.host = process.env.REDIS_HOST || 'localhost'
this.port = process.env.REDIS_PORT || '6379'
this.connected = false
this.client = null
}
getConnection() {
if(this.connected) return this.client
else {
this.client = redis.createClient({
host: this.host,
port: this.port
})
return this.client
}
}
}
// This will be a singleton class. After first connection npm will cache this object for whole runtime.
// Every time you will call this getConnection() you will get the same connection back
module.exports = new Redis()