redisPubClient.js 2.0 KB

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