Redis.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. // 创建 Redis 客户端实例
  8. this.client = redis.createClient({
  9. host: config.redis.host,
  10. port: config.redis.port,
  11. password: config.redis.password || null
  12. });
  13. this.logger = new Logger(path.join(__dirname, '../../logs/Redis.log'), 'INFO');
  14. // 处理连接错误
  15. this.client.on('error', (err) => {
  16. this.logger.error(`Redis连接出错:${err.stack}`);
  17. });
  18. // 确保连接成功
  19. this.client.on('connect', () => {
  20. this.logger.info('Redis连接成功!');
  21. });
  22. // 在连接建立时标记为已连接状态
  23. this.client.on('ready', () => {
  24. this.logger.info('Redis客户端已就绪!');
  25. });
  26. // 在客户端关闭时处理事件
  27. this.client.on('end', () => {
  28. this.logger.warn('Redis客户端连接已关闭!');
  29. });
  30. }
  31. // 获取 Redis 客户端实例
  32. getClient() {
  33. if (!this.client.isOpen) {
  34. this.client.connect().catch((err) => {
  35. this.logger.error(`重新连接Redis时出错:${err.stack}`);
  36. });
  37. }
  38. return this.client;
  39. }
  40. }
  41. const Redis = new RedisClient().getClient();
  42. module.exports = Redis;