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

s3fp2yjn  于 2022-11-21  发布在  Redis
关注(0)|答案(2)|浏览(138)

我只想在Express应用程序启动时连接到redis客户端一次,但我不想使用global
我该怎么做?
谢谢

slhcrj9b

slhcrj9b1#

您可以使用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()
oknrviil

oknrviil2#

Supermacy 的 答案 对 我 不 起 作用 。 这 是 我 想到 的 :

    • 我 的 红色 . js * *
var redis = require('redis');

class Redis {

    constructor() {
        this.host = process.env.REDIS_HOST || '127.0.0.1';
        this.port = process.env.REDIS_PORT || '6379';
        this.connected = false;
        this.client = null;
    }

    async getConnection() {

        var obj = this;

        if(obj.connected) {
            console.log("returning old redis client!");
            return obj.client;
        }
        else {
            obj.client =  redis.createClient({
                host: obj.host,
                port: obj.port
            });

            obj.client.on('connect', function() {
                console.log('Redis Connecting!');
            });

            obj.client.on('ready', function() {
                console.log('Redis Ready!');
                obj.connected = true;
            });

            obj.client.on( 'error', function () {
                console.log('Error: redis disconnected!');
                obj.connected = false;
            });

            obj.client.on( 'end', function () {
                console.log('End: redis connection ended!');
                obj.connected = false;
            });

            try{
                console.log("connecting new redis client!");
                await obj.client.connect();
                obj.connected = true;
                console.log("connected to new redis client!");
            }
            catch(e){
                console.log("redis connect exception caught: " + e);
                return null;
            }
            
            return obj.client;
        }
    }
    
}

module.exports = new Redis();

中 的 每 一 个

  • 示例 用法 : *
const my_redis = require("./my_redis");
const jwt = require("jsonwebtoken");

async function generateJWT_RefreshToken(user_id) {
  const payload = {user_id};
  const token = jwt.sign(payload, process.env.JWT_RT_SECRET, { expiresIn: process.env.JWT_RT_EXP });

  const client = await my_redis.getConnection();
  if(client){
    const res = await client.set(token, 1);
    if(!res) console.log("\nerror adding refresh token to redis: " + err);
    else await client.expire(token, process.env.JWT_RT_EXP_REDIS);
  }

  return token;
}

格式

相关问题