解决办法:使用池连接
Pooling connections
https://www.npmjs.com/package/mysql
Rather than creating and managing connections one-by-one, this module also provides built-in connection pooling using mysql.createPool(config)
. Read more about connection pooling.
Create a pool and use it directly:
var mysql = require('mysql'); var pool = mysql.createPool({ connectionLimit : 10, host : 'example.org', user : 'bob', password : 'secret', database : 'my_db' }); pool.query('SELECT 1 + 1 AS solution', function (error, results, fields) { if (error) throw error; console.log('The solution is: ', results[0].solution); });
This is a shortcut for the pool.getConnection()
-> connection.query()
-> connection.release()
code flow. Using pool.getConnection()
is useful to share connection state for subsequent queries. This is because two calls to pool.query()
may use two different connections and run in parallel. This is the basic structure:
var mysql = require('mysql'); var pool = mysql.createPool(...); pool.getConnection(function(err, connection) { if (err) throw err; // not connected! // Use the connection connection.query('SELECT something FROM sometable', function (error, results, fields) { // When done with the connection, release it. connection.release(); // Handle error after the release. if (error) throw error; // Don't use the connection here, it has been returned to the pool. }); });
If you would like to close the connection and remove it from the pool, use connection.destroy()
instead. The pool will create a new connection the next time one is needed.
Connections are lazily created by the pool. If you configure the pool to allow up to 100 connections, but only ever use 5 simultaneously, only 5 connections will be made. Connections are also cycled round-robin style, with connections being taken from the top of the pool and returning to the bottom.
When a previous connection is retrieved from the pool, a ping packet is sent to the server to check if the connection is still good.