简体   繁体   English

什么时候使用 node-mysql 关闭 MySQL 连接?

[英]When to close MySQL connection using node-mysql?

Currently using: https://github.com/felixge/node-mysql目前使用: https://github.com/felixge/node-mysql

I have the following code:我有以下代码:

var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'me',
    password : 'secret',
    database : 'Database1'
});
app.put('/api/upload', function(req, res, next)
{
    connection.connect();
    doMultipleQueries(function(err)
    {
        connection.end();
    });          
};

The put request works perfectly fine, but calling it the second time, I get the following error put 请求工作得很好,但第二次调用它时,出现以下错误

events.js:68
        throw arguments[1]; // Unhandled 'error' event
                       ^
Error: Cannot enqueue Handshake after invoking quit.
    at Protocol._validateEnqueue (/Users/anon/Desktop/project Web/node_modules/mysql/lib/protocol/Protocol.js:110:16)

Am I supposed to leave the connection open until the server dies?我应该让连接保持打开状态直到服务器死机吗?

UPDATE: When I move the mysql.createConnection into the put request function like so:更新:当我将mysql.createConnection移动到放置请求 function 时,如下所示:

var connection = null; 
app.put('/api/upload', function(req, res, next)
{
    connection = mysql.createConnection({
        host     : 'localhost',
        user     : 'me',
        password : 'secret',
        database : 'Database1'
    });
    connection.connect();
    doMultipleQueries(function(err)
    {
        connection.end();
    });          
};

It works fine.它工作正常。 Does this mean connection.end() closes what mysql.createConnection created and cannot be reconnected?这是否意味着connection.end()关闭了mysql.createConnection创建的内容并且无法重新连接?

Currently using: https://github.com/felixge/node-mysql当前正在使用: https : //github.com/felixge/node-mysql

I have the following code:我有以下代码:

var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'me',
    password : 'secret',
    database : 'Database1'
});
app.put('/api/upload', function(req, res, next)
{
    connection.connect();
    doMultipleQueries(function(err)
    {
        connection.end();
    });          
};

The put request works perfectly fine, but calling it the second time, I get the following error放置请求工作正常,但是第二次调用它,出现以下错误

events.js:68
        throw arguments[1]; // Unhandled 'error' event
                       ^
Error: Cannot enqueue Handshake after invoking quit.
    at Protocol._validateEnqueue (/Users/anon/Desktop/project Web/node_modules/mysql/lib/protocol/Protocol.js:110:16)

Am I supposed to leave the connection open until the server dies?我应该一直保持连接打开直到服务器死机吗?

UPDATE: When I move the mysql.createConnection into the put request function like so:更新:当我将mysql.createConnection移到put请求函数中时,如下所示:

var connection = null; 
app.put('/api/upload', function(req, res, next)
{
    connection = mysql.createConnection({
        host     : 'localhost',
        user     : 'me',
        password : 'secret',
        database : 'Database1'
    });
    connection.connect();
    doMultipleQueries(function(err)
    {
        connection.end();
    });          
};

It works fine.它工作正常。 Does this mean connection.end() closes what mysql.createConnection created and cannot be reconnected?这是否意味着connection.end()关闭了mysql.createConnection创建的内容,并且无法重新连接?

Currently using: https://github.com/felixge/node-mysql当前正在使用: https : //github.com/felixge/node-mysql

I have the following code:我有以下代码:

var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'me',
    password : 'secret',
    database : 'Database1'
});
app.put('/api/upload', function(req, res, next)
{
    connection.connect();
    doMultipleQueries(function(err)
    {
        connection.end();
    });          
};

The put request works perfectly fine, but calling it the second time, I get the following error放置请求工作正常,但是第二次调用它,出现以下错误

events.js:68
        throw arguments[1]; // Unhandled 'error' event
                       ^
Error: Cannot enqueue Handshake after invoking quit.
    at Protocol._validateEnqueue (/Users/anon/Desktop/project Web/node_modules/mysql/lib/protocol/Protocol.js:110:16)

Am I supposed to leave the connection open until the server dies?我应该一直保持连接打开直到服务器死机吗?

UPDATE: When I move the mysql.createConnection into the put request function like so:更新:当我将mysql.createConnection移到put请求函数中时,如下所示:

var connection = null; 
app.put('/api/upload', function(req, res, next)
{
    connection = mysql.createConnection({
        host     : 'localhost',
        user     : 'me',
        password : 'secret',
        database : 'Database1'
    });
    connection.connect();
    doMultipleQueries(function(err)
    {
        connection.end();
    });          
};

It works fine.它工作正常。 Does this mean connection.end() closes what mysql.createConnection created and cannot be reconnected?这是否意味着connection.end()关闭了mysql.createConnection创建的内容,并且无法重新连接?

Rather than creating and managing connections one-by-one, this module also provides built-in connection pooling using mysql.createPool(config).该模块不是一个一个地创建和管理连接,而是使用 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.这是 pool.getConnection() -> connection.query() -> connection.release() 代码流的快捷方式。 Using pool.getConnection() is useful to share connection state for subsequent queries.使用 pool.getConnection() 可用于共享连接 state 以进行后续查询。 This is because two calls to pool.query() may use two different connections and run in parallel.这是因为对 pool.query() 的两次调用可能使用两个不同的连接并并行运行。 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.如果您想关闭连接并将其从池中删除,请改用 connection.destroy()。 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.如果您将池配置为最多允许 100 个连接,但只同时使用 5 个,则只会建立 5 个连接。 Connections are also cycled round-robin style, with connections being taken from the top of the pool and returning to the bottom.连接也是循环的循环方式,连接从池的顶部取出并返回到底部。 Follow this https://github.com/mysqljs/mysql/blob/master/Readme.md#server-disconnects 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.按照这个https://github.com/mysqljs/mysql/blob/master/Readme.md#server-disconnects当从池中检索到以前的连接时,会向服务器发送一个 ping 数据包以检查连接是否仍然存在好的。

otherwise, try the below code否则,请尝试以下代码

const mysql = require("mysql");

var connection;
function handleDisconnect() {
    connection = connection = mysql.createPool({
        host: "localhost",
        user: "xyz",
        password: "xyz",
        database: "xyz",
        multipleStatements: true,
        waitForConnections: true,
        connectionLimit: 100,
    });
    connection.getConnection(function (err) {
        if (err) {
            console.log('error when connecting to db:', err);
            setTimeout(handleDisconnect, 2000);
        }
    });
    connection.on('error', function (err) {
        console.log('db error', err);
        if (err.code === 'PROTOCOL_CONNECTION_LOST') {
            handleDisconnect();
        } else {
            throw err;
        }
    });
}

handleDisconnect();

module.exports = connection;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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