编程技术网

关注微信公众号,定时推送前沿、专业、深度的编程技术资料。

 找回密码
 立即注册

QQ登录

只需一步,快速开始

极客时间

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

Joshua Cook mysql 2022-5-11 10:28 5人围观

腾讯云服务器
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和连接池时连接过多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程技术网(www.editcode.net)!

腾讯云服务器 阿里云服务器
关注微信
^