redis.client.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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.code === 'ECONNREFUSED') {
  27. log.error('连接被拒绝');
  28. }
  29. if (options.times_connected > 10) {
  30. log.error('重试连接超过十次');
  31. }
  32. return Math.max(options.attempt * 100, 3000);
  33. }
  34. this._connection = redis.createClient(
  35. config.redisConfig
  36. );
  37. this._connection.auth(config.redisConfig.password||"",function(){
  38. console.log('通过认证');
  39. });
  40. this._connection.on('connect', function (res) {
  41. log.info('Redis is connected.');
  42. });
  43. this._connection.on('error', function (res) {
  44. log.error("Redis connect failed.");
  45. })
  46. }
  47. get connection() {
  48. return this._connection;
  49. }
  50. static redisClient() {
  51. if (redisClient == null) {
  52. redisClient = new RedisClient();
  53. }
  54. return redisClient;
  55. }
  56. }
  57. function uncaughtExceptionHandler(err){
  58. if(err && err.code == 'ECONNREFUSED'){
  59. //do someting
  60. }else{
  61. process.exit(1);
  62. }
  63. }
  64. process.on('uncaughtException', uncaughtExceptionHandler);
  65. module.exports = RedisClient;