如何使 express.js 应用程序仅在应用程序启动时连接 redis 1 次而不使用全局?

Alo*_*mon 0 redis node.js express

我只想在 Express 应用程序启动时连接到 redis 客户端 1 次,但我不想使用global.

我该怎么做?

谢谢

Sup*_*acy 5

您可以使用 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()
Run Code Online (Sandbox Code Playgroud)