redis.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. 'use strict';
  2. const assert = require('assert');
  3. const awaitFirst = require('await-first');
  4. module.exports = app => {
  5. app.addSingleton('redis', createClient);
  6. };
  7. let count = 0;
  8. function createClient(config, app) {
  9. const Redis = app.config.redis.Redis || require('ioredis');
  10. let client;
  11. if (config.cluster === true) {
  12. assert(config.nodes && config.nodes.length !== 0, '[egg-redis] cluster nodes configuration is required when use cluster redis');
  13. config.nodes.forEach(client => {
  14. assert(client.host && client.port && client.password !== undefined && client.db !== undefined,
  15. `[egg-redis] 'host: ${client.host}', 'port: ${client.port}', 'password: ${client.password}', 'db: ${client.db}' are required on config`);
  16. });
  17. app.coreLogger.info('[egg-redis] cluster connecting');
  18. client = new Redis.Cluster(config.nodes, config);
  19. } else if (config.sentinels) {
  20. assert(config.sentinels && config.sentinels.length !== 0, '[egg-redis] sentinels configuration is required when use redis sentinel');
  21. config.sentinels.forEach(sentinel => {
  22. assert(sentinel.host && sentinel.port,
  23. `[egg-redis] 'host: ${sentinel.host}', 'port: ${sentinel.port}' are required on config`);
  24. });
  25. assert(config.name && config.password !== undefined && config.db !== undefined,
  26. `[egg-redis] 'name of master: ${config.name}', 'password: ${config.password}', 'db: ${config.db}' are required on config`);
  27. app.coreLogger.info('[egg-redis] sentinel connecting start');
  28. client = new Redis(config);
  29. } else {
  30. assert(config.host && config.port && config.password !== undefined && config.db !== undefined,
  31. `[egg-redis] 'host: ${config.host}', 'port: ${config.port}', 'password: ${config.password}', 'db: ${config.db}' are required on config`);
  32. app.coreLogger.info('[egg-redis] server connecting redis://:***@%s:%s/%s',
  33. config.host, config.port, config.db);
  34. client = new Redis(config);
  35. }
  36. client.on('connect', () => {
  37. app.coreLogger.info('[egg-redis] client connect success');
  38. });
  39. client.on('error', err => {
  40. app.coreLogger.error('[egg-redis] client error: %s', err);
  41. app.coreLogger.error(err);
  42. });
  43. app.beforeStart(async () => {
  44. const index = count++;
  45. if (config.weakDependent) {
  46. app.coreLogger.info(`[egg-redis] instance[${index}] is weak dependent and won't block app start`);
  47. client.once('ready', () => {
  48. app.coreLogger.info(`[egg-redis] instance[${index}] status OK`);
  49. });
  50. return;
  51. }
  52. await awaitFirst(client, [ 'ready', 'error' ]);
  53. app.coreLogger.info(`[egg-redis] instance[${index}] status OK, client ready`);
  54. });
  55. return client;
  56. }