Spaces:
Sleeping
Sleeping
| import { Redis } from 'ioredis'; | |
| import dotenv from 'dotenv'; | |
| dotenv.config(); | |
| const redisUrl = process.env.REDIS_URL || 'redis://localhost:6379'; | |
| // 增加连接标志,供其他服务判断是否可用 | |
| export let isRedisAvailable = false; | |
| export const redis = new Redis(redisUrl, { | |
| maxRetriesPerRequest: null, | |
| lazyConnect: true, // 延迟连接,避免启动时立即报错 | |
| retryStrategy(times) { | |
| const delay = Math.min(times * 50, 2000); | |
| // 如果重试次数过多且依然连不上,降低频率 | |
| if (times > 10) return null; // 停止重试,标记不可用 | |
| return delay; | |
| }, | |
| }); | |
| redis.on('connect', () => { | |
| isRedisAvailable = true; | |
| console.log('[Redis] 已连接'); | |
| }); | |
| redis.on('error', (err) => { | |
| isRedisAvailable = false; | |
| // 只在第一次报错时打印详细信息,避免日志淹没 | |
| if (redis.status === 'reconnecting') { | |
| // console.log('[Redis] 正在尝试重连...'); | |
| } else { | |
| console.warn('[Redis] 连接失败,部分高并发与队列功能将受限'); | |
| } | |
| }); | |
| export default redis; | |