import { Redis } from 'ioredis'; import { config } from './config.ts'; const redisConfig = { host: config.REDIS_HOST || 'localhost', port: parseInt(config.REDIS_PORT || '6379'), password: config.REDIS_PASSWORD, }; export const createRedisClient = (options = {}) => { const redisClient = new Redis({ host: 'localhost', // Redis 服务器的主机名或 IP 地址 port: 6379, // Redis 服务器的端口号 // password: 'your_password', // Redis 的密码 (如果有) db: 0, // 要使用的 Redis 数据库索引 (0-15) keyPrefix: '', // key 前缀 retryStrategy(times) { // 连接重试策略 return Math.min(times * 50, 2000); // 每次重试时延迟增加 }, maxRetriesPerRequest: null, // 允许请求重试的次数 (如果需要无限次重试) ...redisConfig, ...options, }); return redisClient; }; // 配置 Redis 连接 export const redis = createRedisClient(); // 监听连接事件 redis.on('connect', () => { console.log('Redis 连接成功'); }); redis.on('error', (err) => { console.error('Redis 连接错误', err); }); // 初始化 Redis 客户端 export const redisPublisher = createRedisClient(); // 用于发布消息 export const redisSubscriber = createRedisClient(); // 用于订阅消息