简体   繁体   中英

Running SLS Functions Locally for Unit Tests Results in Node Mysql Connection Pool 'Too Many Connections'

I'm relatively new to Serverless and have been running my function locally for use with my Jest unit tests. Using Node-Mysql I'm creating a connection pool by calling mysql.createPool, and then subsequently calling pool.query any time I need to do a query. I'm working under the assumption that pool.query actually is a shortcut to call pool.getConnection, connection.query and finally connection.release. Thereby making the connections available again once they have finished processing the query.

The problem I'm having is when I run my unit tests, they all run the first time but if ran a second time they are failing due to 'Error: ER_CON_COUNT_ERROR: Too many connections'.

We don't get the same issue when the function is hosted in AWS Lambda.

Has anybody experienced anything like this, or does anybody have any suggested work arounds to mitigate this as a local-only issue?

You need to call pool.end to close all the pool connections on your end. Otherwise the connection are open until the MySql server closes them.

From the node-mysql readme :

When you are done using the pool, you have to end all the connections or the Node.js event loop will stay active until the connections are closed by the MySQL server.

This likely doesn't happen in production because AWS Lambda makes an attempt to reuse execution environments, so in practice only a few executions create a new pool and open new connections.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM