You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js MariaDB程序调用conn.end()后挂起无法退出求助

程序挂起无法退出的原因及解决方法

核心问题分析

  1. 连接释放方式错误:从连接池获取的连接,调用conn.end()会直接关闭该连接,而非归还到连接池。但更关键的是,连接池默认会维持若干空闲连接,这些连接会让Node.js事件循环保持活跃,阻止程序自动退出。
  2. 未显式关闭连接池:即使正确归还连接,连接池的空闲连接仍会占用资源,导致程序无法正常退出,必须显式关闭连接池释放所有资源。

修正后的代码

const mariadb = require('mariadb');

const pool = mariadb.createPool({
    host: '127.0.0.1',
    user: 'admin',
    password: 'adminpassword',
    port: 3306,
    connectionLimit: 5,
    connectTimeout: 1000
});

async function asyncFunction() {
    let conn;
    try {
        console.log('get connection');
        conn = await pool.getConnection();
        const rows = await conn.query("SELECT 1 as val");
        console.log(rows);
        console.log('done with that');
    } catch (err) {
        console.log('got error');
        throw err;
    } finally {
        if (conn) {
            console.log('release connection back to pool');
            // 归还连接到连接池,而非直接关闭
            conn.release();
        } else {
            console.log('nothing to release');
        }
    }

    console.log('exit?');
}

// 执行异步函数后关闭连接池,释放所有资源
asyncFunction()
    .catch(err => console.error(err))
    .finally(() => pool.end());

修正说明

  • 把conn.end()替换为conn.release():将连接归还到连接池,供后续请求复用,而非直接销毁连接。
  • 在异步函数执行完成后调用pool.end():关闭整个连接池,释放所有空闲连接,让Node.js事件循环可以正常结束,程序随之退出。

内容的提问来源于stack exchange,提问作者user2138149

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 19:50:12