redisPubClient.js 2.1 KB

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