Skip to content

游标未关闭:资源泄漏

快速摘要

你打开了游标但未关闭它 —— 数据库会保持游标及其资源分配直到会话结束。

为什么发生

  • 为迭代结果打开了游标但循环后从未显式关闭

  • 游标关闭语句之前发生异常,导致游标保持打开

  • 游标在一个提前返回的函数中打开,未关闭游标就返回了

最小示例

✗ 错误代码
async function getItems() {
  const cursor = db.collection('items').find({});
  while (await cursor.hasNext()) {
    const item = await cursor.next();
    if (item.invalid) return []; // early return, cursor not closed!
  }
}
✓ 修复代码
async function getItems() {
  const cursor = db.collection('items').find({});
  try {
    const items = [];
    while (await cursor.hasNext()) {
      const item = await cursor.next();
      if (item.invalid) return [];
      items.push(item);
    }
    return items;
  } finally {
    await cursor.close(); // always closed
  }
}

使用 try/finally 确保即使提前返回或异常也关闭游标,防止资源泄漏。

如何诊断

  • 在数据库会话监控视图或系统目录中检查打开的游标

  • 查看打开游标的代码并验证每个游标在所有代码路径中都有对应关闭

  • 监控连接池使用量是否有稳定增长,指示游标或连接泄漏

如何修复

  • 使用 try/finally 块确保即使发生异常也关闭游标

  • 使用上下文管理器或 resource-with 模式自动关闭游标

  • 在数据库上设置游标超时,在一段时间后自动关闭空闲游标

如何预防

  • 始终使用 try/finally 或上下文管理器保证所有代码路径中的游标清理

  • 监控打开游标数量并设置限制以在耗尽资源前检测泄漏

相关资源

相关术语

相关课程

← 返回语言