我只想在我的 express 应用程序启动时连接到 redis 客户端 1 次,但我不想使用 global
。
我该怎么做?
谢谢
最佳答案
您可以使用 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()
关于node.js - 如何使 express.js 应用程序在不使用全局的情况下启动时仅连接 redis 1 次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54240635/