/** * Redis客户端封装。 * * 注意Redis使用Promises保证调用流程。 * * https://github.com/NodeRedis/node_redis * * author: linzhuo * since: 2016/12/09 */ "use strict"; let redis = require('redis'); let Promise = require('bluebird'); let configFile = require('../../include/commons').CONFIG_FILE; let config = require('../../resources/config/' + configFile); let log = require("../../util/log.js"); let redisClient = null; // 启用promises Promise.promisifyAll(redis.RedisClient.prototype); Promise.promisifyAll(redis.Multi.prototype); class RedisClient { constructor() { var redisConfig = config.redisConfig; redisConfig.retry_strategy = function(options){ log.info("重新连接次数:"+options.times_connected); if (options.error && options.error.code === 'ECONNREFUSED') { log.error('连接被拒绝'); } if (options.total_retry_time > 1000 * 60 * 60) { log.error('重试时间耗尽'); } if (options.times_connected > 10) { log.error('重试连接超过十次'); } return Math.max(options.attempt * 100, 3000); } this._connection = redis.createClient( config.redisConfig ); this._connection.auth(config.redisConfig.password||"",function(){ console.log('通过认证'); }); this._connection.on('connect', function (res) { log.info('Redis is connected.'); }); this._connection.on('error', function (res) { log.error("Redis connect failed."); }) } get connection() { return this._connection; } static redisClient() { if (redisClient == null) { redisClient = new RedisClient(); } return redisClient; } } function uncaughtExceptionHandler(err){ if(err && err.code == 'ECONNREFUSED'){ //do someting }else{ log.error(err+"exit in redis"); } } process.on('uncaughtException', uncaughtExceptionHandler); module.exports = RedisClient;