简体   繁体   中英

How to ensure connection.end() is called when obtaining a database connection from a pool

We are using node-mysql and I'm exposing createPool of mysql where from any file, we can require the database file and obtain a connection like this

var db = ("./database");

db(function(err, connection) {
   //use connection to do stuff
}

I noticed that people don't always remember to call connection.end() that would return the connection to the pool and then we hit the limit..

How can I design the acquiring of the connection so that no matter when they decide to terminate the callback function that the connection.end() is called? I can't figure out a way to make a single place where we can do this so developers are only concerned with getting the connection..

I don't know the createPool from mysql, but can't you just wrap it?

People will provide a function stuff(err, connection) { ... do whatever they want ... } . Why don't you take that function and create a save_stuff -function? Something like

function save_stuff_creator(stuff) {
    return function(err, connection) { stuff(err, connection); connection.end() }
}

You maybe want some try..catch around the stuff() -call.

If you want the connection to stay with someone for some other callbacks, you could modify the function to something like stuff(connection, callback) and use a module like async and a series -Object.

But I have no idea how to enforce a final call of connection.end() if you want to wait for the end of "the user thread": that is actually the issue. There is no such thread and there is no way of figuring out which event in the event loop comes from whom. As far as I know the event loop is not exposed to the js-developer.

If you can't trust your callee, maybe you can put his code in an extra child node (see module cluster . So you have a bit of control: when the child finishes you become notified.

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