Redis.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. const redis = require('redis');
  2. const config = require('../../config.json');
  3. const Logger = require('../../lib/Logger');
  4. const path = require('path');
  5. class RedisClient {
  6. constructor() {
  7. // node-redis v4 必须使用 socket 或 url,顶层 host/port 会被忽略并默认连 127.0.0.1:6379
  8. const clientOptions = {
  9. socket: {
  10. host: config.redis.host,
  11. port: config.redis.port
  12. }
  13. };
  14. if (config.redis.password) {
  15. clientOptions.password = config.redis.password;
  16. }
  17. this.client = redis.createClient(clientOptions);
  18. this.logger = new Logger(path.join(__dirname, '../../logs/Redis.log'), 'INFO');
  19. this.logger.info(`Redis 目标:${config.redis.host}:${config.redis.port}`);
  20. // 处理连接错误
  21. this.client.on('error', (err) => {
  22. this.logger.error(`Redis连接出错:${err?.message || err?.stack || err}`);
  23. });
  24. // 确保连接成功
  25. this.client.on('connect', () => {
  26. this.logger.info('Redis连接成功!');
  27. });
  28. // 在连接建立时标记为已连接状态
  29. this.client.on('ready', () => {
  30. this.logger.info('Redis客户端已就绪!');
  31. });
  32. // 在客户端关闭时处理事件
  33. this.client.on('end', () => {
  34. this.logger.warn('Redis客户端连接已关闭!');
  35. });
  36. }
  37. // 获取 Redis 客户端实例
  38. getClient() {
  39. if (!this.client.isOpen) {
  40. this.client.connect().catch((err) => {
  41. this.logger.error(`重新连接Redis时出错:${err?.message || err?.stack || err}`);
  42. });
  43. }
  44. return this.client;
  45. }
  46. }
  47. const Redis = new RedisClient().getClient();
  48. module.exports = Redis;