redis.client.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /**
  2. * Redis客户端封装。
  3. *
  4. * 注意Redis使用Promises保证调用流程。
  5. *
  6. * https://github.com/NodeRedis/node_redis
  7. *
  8. * author: linzhuo
  9. * since: 2016/12/09
  10. */
  11. "use strict";
  12. let redis = require('redis');
  13. let Promise = require('bluebird');
  14. let configFile = require('../../include/commons').CONFIG_FILE;
  15. let config = require('../../resources/config/' + configFile);
  16. let log = require("../../util/log.js");
  17. let redisClient = null;
  18. // 启用promises
  19. Promise.promisifyAll(redis.RedisClient.prototype);
  20. Promise.promisifyAll(redis.Multi.prototype);
  21. class RedisClient {
  22. constructor() {
  23. var redisConfig = config.redisConfig;
  24. redisConfig.retry_strategy = function(options){
  25. log.info("重新连接次数:"+options.times_connected);
  26. if (options.error && options.error.code === 'ECONNREFUSED') {
  27. log.error('连接被拒绝');
  28. }
  29. if (options.total_retry_time > 1000 * 60 * 60) {
  30. log.error('重试时间耗尽');
  31. }
  32. if (options.times_connected > 10) {
  33. log.error('重试连接超过十次');
  34. }
  35. return Math.max(options.attempt * 100, 3000);
  36. }
  37. this._connection = redis.createClient(
  38. config.redisConfig
  39. );
  40. this._connection.auth(config.redisConfig.password||"",function(){
  41. console.log('通过认证');
  42. });
  43. this._connection.on('connect', function (res) {
  44. log.info('Redis is connected.');
  45. });
  46. this._connection.on('error', function (res) {
  47. log.error("Redis connect failed.");
  48. })
  49. }
  50. get connection() {
  51. return this._connection;
  52. }
  53. static redisClient() {
  54. if (redisClient == null) {
  55. redisClient = new RedisClient();
  56. }
  57. return redisClient;
  58. }
  59. }
  60. function uncaughtExceptionHandler(err){
  61. if(err && err.code == 'ECONNREFUSED'){
  62. //do someting
  63. }else{
  64. log.error(err+"exit in redis");
  65. }
  66. }
  67. process.on('uncaughtException', uncaughtExceptionHandler);
  68. module.exports = RedisClient;