Redis.js 931 B

12345678910111213141516171819202122232425262728293031323334
  1. const redis = require('redis');
  2. const config = require('../../config.json');
  3. const Logger = require('../../lib/Logger');
  4. class RedisClient {
  5. constructor() {
  6. // 创建 Redis 客户端实例
  7. this.client = redis.createClient({
  8. host: config.redis.host,
  9. port: config.redis.port,
  10. password: config.redis.password || null
  11. });
  12. this.logger = new Logger(path.join(__dirname, '../../logs/Redis.log'), 'INFO');
  13. // 处理连接错误
  14. this.client.on('error', (err) => {
  15. this.logger.error(`Redis连接出错:${err.stack}`);
  16. });
  17. // 确保连接成功
  18. this.client.on('connect', () => {
  19. this.logger.info('Redis连接成功!');
  20. });
  21. }
  22. // 获取 Redis 客户端实例
  23. getClient() {
  24. return this.client;
  25. }
  26. }
  27. const Redis = new RedisClient().getClient();
  28. module.exports = Redis;