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