node.js - 如何使 express.js 应用程序在不使用全局的情况下启动时仅连接 redis 1 次?

标签 node.js express redis

我只想在我的 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/

相关文章:

java - JRedis future 稳定

node.js - 多个监听器从 NodeJS 中的同一流读取

javascript - 使用提供的演示设置 Mongoose 不起作用

Java 代码 Cipher.doFinal(byte[]) 的 Javascript/NodeJS 等效代码?

javascript - AWS Lambda 中的 FTP - 下载文件时出现问题(异步/等待)

node.js - 如何使用 Knex 获取与我正在查询的表相关的行

javascript - 如何使用 express router 正确调用 passport.js 函数?

node.js, express.js - 提供单个静态文件的最简单方法是什么?

node.js - Socket.io断开连接和redis

python - 如何在 Django 中使用 redis?