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

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

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

  1. bluebird.promisifyAll(redis);
  2. declare module 'redis' {
  3. export interface RedisClient extends NodeJS.EventEmitter {
  4. scanAsync(...args: any[]): Promise<any>;
  5. HSETAsync(...args: any[]): Promise<any>;
  6. keysAsync(...args: any[]): Promise<any>;
  7. hgetallAsync(...args: any[]): Promise<any>;
  8. getAsync(...args: any[]): Promise<any>;
  9. delAsync(...args: any[]): Promise<any>;
  10. quitAsync(): Promise<any>;
  11. }
  12. }
  13. /**
  14. * Setup connection to redis instance
  15. *
  16. * @category Redis
  17. *
  18. * @returns {Promise<RedisClient|Error>} resolves to a redisclient, reject to error
  19. */
  20. export function connectToRedis(url: string): redis.RedisClient {
  21. const client = redis.createClient({
  22. url,
  23. });
  24. client.on('connect', (): void => {
  25. logger.info(`Connected to Redis ${url}`);
  26. });
  27. client.on('error', (): void => {
  28. logger.info('Unable to connect to Redis, check to see if docker image is running');
  29. throw new CacheException('Unable to connect to Redis');
  30. });
  31. return client;
  32. }
  33. /**
  34. * Closes connection to redis gracefully
  35. *
  36. * @category Redis
  37. *
  38. * @param {RedisClient} client redisclient to close
  39. */
  40. export function closeRedisConnection(client: redis.RedisClient): Promise<void> {
  41. return new Promise((resolve): void => {
  42. console.log('IM TRYING TO CLOSE THIS SHIT');
  43. client.quit((): void => {
  44. logger.info('Closed connection to Redis');
  45. resolve();
  46. });
  47. });
  48. }
  49. export const redisClient = connectToRedis('process.env.REDIS_URL');

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

暂无答案!

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

相关问题