当数据库连接失败时,如何实现自动重连和告警?

解读

国内线上环境对可用性要求极高,面试官想确认两点:

  1. 你是否了解 MikroORM 在 Node.js 进程里“连接”与“连接池”的真实生命周期;
  2. 你是否能把“重连”与“告警”做成可灰度、可观测、可回滚的生产级方案,而不是简单 try/catch。
    因此,回答必须给出“检测—重连—告警”闭环,并兼顾 TypeScript 类型安全、微服务多实例场景以及国内常用的飞书/钉钉/企业微信告警通道。

知识点

  1. MikroORM 的 Connection 与 EntityManager 解耦:连接异常抛出后 EntityManager 仍存活,可重新注入新连接。
  2. 连接池由底层驱动(pg、mysql2、mongodb)管理,MikroORM 只暴露 MikroORM.isConnected() 与 orm.close()/orm.connect()。
  3. 进程级心跳:利用 setInterval 定时 SELECT 1(或 MongoDB ping),失败次数达阈值触发重连。
  4. 重连退避:指数退避 + 最大重试上限,防止雪崩。
  5. 告警分级:
    • 首次失败:WARN 级日志 + 飞书机器人;
    • 连续 N 次仍失败:ERROR 级日志 + 电话告警(阿里云语音/腾讯云短信)。
  6. 可观测:统一使用国内可落地的 Pino + Loki 或 SLS,TraceId 贯穿请求与重连动作。
  7. 零停机发布:在 k8s 就绪探针里检测 orm.isConnected(),未就绪即摘除流量,避免用户感知抖动。

答案

生产级落地代码(TypeScript,以 PostgreSQL 为例,MongoDB 同理替换 ping 语句):

// orm.config.ts
const config: Options = {
  type: 'postgresql',
  host: process.env.PG_HOST,
  port: +process.env.PG_PORT!,
  dbName: process.env.PG_DB,
  user: process.env.PG_USER,
  password: process.env.PG_PWD,
  pool: {
    min: 2,
    max: 10,
    acquireTimeoutMillis: 3000,
    createTimeoutMillis: 3000,
    propagateCreateError: false, // 关键:第一次建连失败不抛错,由上层重试
  },
  logger: logger.log.bind(logger),
  findOneOrFailHandler: (entityName) => new NotFoundException(entityName),
};

// heartbeat.service.ts
@Injectable()
export class HeartbeatService implements OnApplicationBootstrap, OnApplicationShutdown {
  private orm: MikroORM;
  private timer: NodeJS.Timer | null = null;
  private failCount = 0;
  private readonly maxFails = +process.env.DB_HEARTBEAT_MAX_FAILS! || 5;
  private readonly baseDelay = 1000; // 1s

  constructor(private readonly alertService: AlertService) {}

  async onApplicationBootstrap() {
    this.orm = await MikroORM.init(config);
    this.startHeartbeat();
  }

  private startHeartbeat() {
    this.timer = setInterval(async () => {
      try {
        await this.orm.em.getConnection().execute('SELECT 1');
        if (this.failCount > 0) {
          this.alertService.send('DB_RECOVER', '数据库已恢复');
          this.failCount = 0;
        }
      } catch (e) {
        this.failCount++;
        logger.warn({ failCount: this.failCount }, 'heartbeat failed');
        if (this.failCount === 1) {
          this.alertService.send('DB_WARN', '数据库心跳首次失败');
        }
        if (this.failCount >= this.maxFails) {
          this.alertService.send('DB_CRITICAL', '数据库连续失败达阈值,即将重连');
          await this.reconnect();
        }
      }
    }, 5000);
  }

  private async reconnect() {
    try {
      await this.orm.close(); // 先优雅关闭旧连接池
    } catch (e) {
      /* ignore */
    }
    let retry = 0;
    const maxRetry = 7;
    while (retry < maxRetry) {
      try {
        await this.orm.connect();
        this.failCount = 0;
        this.alertService.send('DB_RECONNECT_SUCCESS', '重连成功');
        return;
      } catch (e) {
        const delay = this.baseDelay * Math.pow(2, retry);
        logger.error({ retry, delay }, 'reconnect failed, will retry');
        await new Promise((r) => setTimeout(r, delay));
        retry++;
      }
    }
    // 走到这里说明彻底连不上,触发 P1 告警并退出进程,由 k8s 重新调度
    this.alertService.callPhone('数据库重连彻底失败,请人工介入');
    process.exit(1);
  }

  async onApplicationShutdown() {
    this.timer && clearInterval(this.timer);
    await this.orm.close();
  }
}

// alert.service.ts(飞书机器人示例)
@Injectable()
export class AlertService {
  private readonly robot = process.env.FEISHU_ROBOT_URL!;
  async send(level: 'DB_WARN' | 'DB_CRITICAL' | 'DB_RECOVER' | 'DB_RECONNECT_SUCCESS', text: string) {
    const body = {
      msg_type: 'text',
      content: { text: `[${level}] ${text} @${new Date().toLocaleString('zh-CN')}` },
    };
    await fetch(this.robot, { method: 'POST', body: JSON.stringify(body), headers: { 'Content-Type': 'application/json' } });
  }
  async callPhone(text: string) {
    // 调用阿里云语音接口,略
  }
}

关键配置项说明

  1. propagateCreateError: false 让首次建连失败不抛错,交给心跳层统一重试。
  2. 指数退避最大 7 次,总耗时约 2 分钟,仍失败即认为网络或 DBA 变更问题,直接退出进程,由 k8s 重新调度到其他节点。
  3. 就绪探针 /health/db 直接返回 orm.isConnected(),防止未就绪 Pod 被塞流量。

拓展思考

  1. 双活/多活架构:若使用阿里云 PolarDB 读写分离,可在重连时动态切换只读节点,需把 host 抽成配置中心(Nacos/Apollo)热更新。
  2. 事务级重试:MikroORM 的 em.transactional() 遇到 ConnectionException 可自动重放整个事务,需配合幂等键(如业务订单号)防止重复写。
  3. 灰度重连:利用配置中心开关,先让 10% 实例开启重连逻辑,观测 30 分钟无误后全量,避免代码 bug 导致大面积重启。
  4. 成本优化:心跳语句可换成 /* PING */ 注释 SQL,方便 DBA 在慢日志里直接过滤,减少无用审计数据。