nodejsmysql 오류: Connection lost 서버가 연결을 닫았습니다.
노드 mysql을 사용하면 서버에 의해 TCP 연결이 셧다운된다는 오류가 12:00 ~2:00 사이에 나타납니다.메시지 전문은 다음과 같습니다.
Error: Connection lost: The server closed the connection.
at Protocol.end (/opt/node-v0.10.20-linux-x64/IM/node_modules/mysql/lib/protocol/Protocol.js:73:13)
at Socket.onend (stream.js:79:10)
at Socket.EventEmitter.emit (events.js:117:20)
at _stream_readable.js:920:16
at process._tickCallback (node.js:415:13)
해결책이 있다.하지만 이렇게 시도해보니 문제가 발생하기도 합니다.지금 나는 어떻게 해야 할지 모르겠다.이 문제를 겪고 있는 사람이 있나요?
다음은 솔루션에 따라 작성한 방법입니다.
var handleKFDisconnect = function() {
kfdb.on('error', function(err) {
if (!err.fatal) {
return;
}
if (err.code !== 'PROTOCOL_CONNECTION_LOST') {
console.log("PROTOCOL_CONNECTION_LOST");
throw err;
}
log.error("The database is error:" + err.stack);
kfdb = mysql.createConnection(kf_config);
console.log("kfid");
console.log(kfdb);
handleKFDisconnect();
});
};
handleKFDisconnect();
다음 코드를 사용하여 서버 연결 해제를 처리해 보십시오.
var db_config = {
host: 'localhost',
user: 'root',
password: '',
database: 'example'
};
var connection;
function handleDisconnect() {
connection = mysql.createConnection(db_config); // Recreate the connection, since
// the old one cannot be reused.
connection.connect(function(err) { // The server is either down
if(err) { // or restarting (takes a while sometimes).
console.log('error when connecting to db:', err);
setTimeout(handleDisconnect, 2000); // We introduce a delay before attempting to reconnect,
} // to avoid a hot loop, and to allow our node script to
}); // process asynchronous requests in the meantime.
// If you're also serving http, display a 503 error.
connection.on('error', function(err) {
console.log('db error', err);
if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
handleDisconnect(); // lost due to either server restart, or a
} else { // connnection idle timeout (the wait_timeout
throw err; // server variable configures this)
}
});
}
handleDisconnect();
당신의 코드에 따르면 다음 부품이 누락되어 있습니다.connection = mysql.createConnection(db_config);
이 메커니즘의 원래 사용 사례는 기억나지 않습니다.요즘은 유효한 사용 사례가 생각나지 않는다.
클라이언트는 연결 끊김을 감지하고 연결을 다시 만들 수 있어야 합니다.프로그램 로직의 일부가 동일한 연결을 사용하여 실행되는 것이 중요한 경우 트랜잭션을 사용하십시오.
tl;dr; 이 방법을 사용하지 마십시오.
실용적인 해결책은 MySQL이 연결을 유지하도록 강제하는 것입니다.
setInterval(function () {
db.query('SELECT 1');
}, 5000);
이 솔루션은 접속의 존재를 인식하는 방법으로 코드를 구조화할 필요가 없기 때문에 접속 풀이나 처리의 절단보다 선호됩니다.5초마다 쿼리를 작성하면 접속이 활성화되고PROTOCOL_CONNECTION_LOST발생하지 않습니다.
게다가 이 방법을 사용하면, 재접속이 아니고, 같은 접속을 계속 유지할 수 있습니다.이게 중요해요.스크립트에 의존할 경우 어떤 일이 일어날지 고려합니다.LAST_INSERT_ID()mysql 접속이 리셋되어 있는 것을 알 수 없는 것입니까?
다만, 이것에 의해, 접속의 타임 아웃이 보증됩니다(wait_timeout그리고.interactive_timeout)는 발생하지 않습니다.다른 모든 시나리오에서는 예상대로 실패합니다.따라서 다른 오류는 반드시 처리해 주십시오.
더 나은 해결책은 수영장을 사용하는 것입니다. 수영장이 이 문제를 해결해 줄 것입니다.
const pool = mysql.createPool({
host: 'localhost',
user: '--',
database: '---',
password: '----'
});
// ... later
pool.query('select 1 + 1', (err, rows) => { /* */ });
https://github.com/sidorares/node-mysql2/issues/836
끊어진 연결 시도를 시뮬레이션하려면 다음과 같이 하십시오.
connection.destroy();
상세한 것에 대하여는, https://github.com/felixge/node-mysql/blob/master/Readme.md#terminating-connections 를 참조해 주세요.
각 쿼리의 연결을 만들고 파괴하는 작업은 복잡할 수 있습니다. MySQL 대신 MariaDB를 설치하기로 결정했을 때 서버 마이그레이션에 문제가 있었습니다.파일 etc/my.cnf의 어떤 이유로 인해 wait_timeout 파라미터의 기본값은 10초입니다(이것은 지속성을 구현할 수 없는 원인이 됩니다).그 후, 솔루션은 28800으로 설정되었습니다.즉, 8시간입니다.음, 이 "귀보나다"에 대해 누군가 도와줬으면 좋겠는데...영어가 서툴러서 죄송합니다.
언급URL : https://stackoverflow.com/questions/20210522/nodejs-mysql-error-connection-lost-the-server-closed-the-connection
'programing' 카테고리의 다른 글
| HttpURL 접속 타임아웃 설정 (0) | 2022.09.21 |
|---|---|
| python re.sub 그룹: \number 뒤의 숫자 (0) | 2022.09.21 |
| PHP는 속성이 개체 또는 클래스에 있는지 확인합니다. (0) | 2022.09.20 |
| 가입 시 특정 사용자에 대한 문서를 표시하는 SQL 조회 (0) | 2022.09.20 |
| 자바에서 스크린샷을 찍어서 이미지 같은 것에 저장하는 방법이 있나요? (0) | 2022.09.20 |