示例化redis客户端的正确方法是什么?

nc1teljy  于 2021-06-09  发布在  Redis
关注(0)|答案(0)|浏览(279)

我在弄清楚如何通过节点redis正确设置redis基础设施时遇到了一些问题。我正在使用以下代码设置我的全局客户端:

bluebird.promisifyAll(redis);

declare module 'redis' {
  export interface RedisClient extends NodeJS.EventEmitter {
    scanAsync(...args: any[]): Promise<any>;
    HSETAsync(...args: any[]): Promise<any>;
    keysAsync(...args: any[]): Promise<any>;
    hgetallAsync(...args: any[]): Promise<any>;
    getAsync(...args: any[]): Promise<any>;
    delAsync(...args: any[]): Promise<any>;
    quitAsync(): Promise<any>;
  }
}

/**
 * Setup connection to redis instance
 *
 * @category Redis
 *
 * @returns {Promise<RedisClient|Error>} resolves to a redisclient, reject to error
 */
export function connectToRedis(url: string): redis.RedisClient {
  const client = redis.createClient({
    url,
  });

  client.on('connect', (): void => {
    logger.info(`Connected to Redis ${url}`);
  });

  client.on('error', (): void => {
    logger.info('Unable to connect to Redis, check to see if docker image is running');
    throw new CacheException('Unable to connect to Redis');
  });
  return client;
}

/**
 * Closes connection to redis gracefully
 *
 * @category Redis
 *
 * @param {RedisClient} client redisclient to close
 */
export function closeRedisConnection(client: redis.RedisClient): Promise<void> {
  return new Promise((resolve): void => {
    console.log('IM TRYING TO CLOSE THIS SHIT');
    client.quit((): void => {
      logger.info('Closed connection to Redis');
      resolve();
    });
  });
}

export const redisClient = connectToRedis('process.env.REDIS_URL');

这个实现背后的想法是,我将在整个应用程序中使用一个全局redis客户机。
上面的代码正是我需要它做的,但似乎这会导致我的jest测试挂起。有没有更好(或正确)的方法来处理这些redis连接?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题