npm mysql2:使用Promise和连接池时连接过多 [英] npm mysql2: Too many connections when using promises and a connection pool

查看:36
本文介绍了npm mysql2:使用Promise和连接池时连接过多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用mysql2/promise模块,我正在创建一个连接池,如下所示:

Using the mysql2/promise module, I'm creating a connection pool like this:

import mysql from 'mysql2/promise';

async function getConnection() {
    let pool = await mysql.createPool({
        connectionLimit: 10,
        host:'localhost',
        user: 'root',
        database: 'customers'
    });

    return pool.getConnection();
}

export  {
    getConnection
};

在另一个文件中,我正在这样访问此功能:

In another file, I am access this functionality like this:

import {getConnection} from '../config/database/mysql';

async function getCustomerAddresses(id){
    let conn = await getConnection();

    let [rows, fields] = await conn.execute(
        `SELECT *
        FROM addresses WHERE customer = ?`, [id]);

    conn.release();

    return rows;
}

多次调用该函数后,出现以下错误:

After calling the function a couple of times, I'm getting the following error:

连接过多

我做错了什么?还有一种更优雅的方法,这样我就不必在每个函数中都包含getConnection()调用了吗?

What am I doing wrong? And is there a more elegant way so I don't have to include the getConnection() call in every function?

推荐答案

每次您要建立新连接时都在创建新池,尽管最终池是GCed连接仍处于打开状态,除非您手动调用 .close().您真正应该做的是只有一个池,它将为您管理连接的生命周期:

You are creating new pool each time you want new connection, and though pool is eventually is GCed connection is still open unless you manually call .close() on it. What you should really do is to have one single pool and it will manage connections lifetime for you:

import mysql from 'mysql2/promise';

const pool = mysql.createPool(params);  
const getConnection = () => pool.getConnection();
export { getConnection } 

这篇关于npm mysql2:使用Promise和连接池时连接过多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆