1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- /**
- * 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.code === 'ECONNREFUSED') {
- 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{
- process.exit(1);
- }
- }
- process.on('uncaughtException', uncaughtExceptionHandler);
- module.exports = RedisClient;
|