redis 连接工厂 - 这会导致内存泄漏吗?

redis connection factory - will this cause memory leaks?

希望有人能给我一些建议

我创建了一个模块,它基本上使用也使用 promises 的单例模式创建了一个 redis 连接。

但是,在我 return 连接 redis 之前,我首先检查连接是否就绪,在就绪事件上,我解决了承诺,同样,在任何错误上,我拒绝了承诺。

我唯一关心的是这个方法,我是否可以引入内存泄漏,因为侦听器函数就绪,错误可能会在承诺完成后继续很好地侦听,应该由垃圾收集器清理。

我不确定这是否会造成某种内存泄漏..

如有任何建议,我们将不胜感激。

   

    import redis from 'redis';
       import redisearch from 'redis-redisearch';
    
       redisearch(redis);
    
       let redisClient: redis.RedisClient = null;
    
    
       export function getRedisClient(): Promise {
    
    
        return new Promise((resolve: any, reject: any) => {
    
            if (redisClient && redisClient.connected) {
                return resolve(redisClient);
            }
    
            redisClient = redis.createClient({
    
                password: process.env.REDIS_PASSWORD,
    
                retry_strategy: function (options) {
                    if (options.error && options.error.code === "ECONNREFUSED") {
                        // End reconnecting on a specific error and flush all commands with
                        // a individual error
                        return new Error("The server refused the connection");
                    }
                    if (options.total_retry_time > 1000 * 60 * 60) {
                        // End reconnecting after a specific timeout and flush all commands
                        // with a individual error
                        return new Error("Retry time exhausted");
                    }
                    if (options.attempt > 10) {
                        // End reconnecting with built in error
                        return undefined;
                    }
                    // reconnect after
                    return Math.min(options.attempt * 100, 3000);
                },
            });
    
            redisClient.on("ready", function (error: any) {
                console.log("connection is good");
                return resolve(redisClient);
            });
    
            redisClient.on("error", function (error: any) {
                console.log("reject error");
                if (redisClient) {
                    redisClient.end(false);
                    redisClient = null;
                    return reject(error);
                }
    
            });
        })
    }

如果在任何 redisClient 完成连接之前多次调用 getRedisClient,则此模式可以创建多个 redisClient。一个稍微简单的模式可能是缓存 Promise<RedisClient> 而不是 redisClient:

let redisClientP: Promise<RedisClient>;
function getRedisClient (): Promise<RedisClient> {
  if (redisClientP) return redisClientP;
  redisClientP = new Promise(...previous code)
  return redisClientP;
}

如果您以前没有见过这种类型的缓存 Promise 用法,这里有一个小片段演示了您可以多次访问 Promise 上的 .then

const p = new Promise((resolve) => resolve(2));


(async function main () {
  for (let i = 0; i < 100; i++) {
    console.log(i, await p); 
  }
})()