NodeJS + ExpressJS에서 mysql DB에 대한 연결을 관리하는 올바른 방법
React JS / Node JS + Express를 사용하여 응용 프로그램을 개발 중입니다.JS.
데이터베이스 접속을 처리하는 가장 좋은 방법이 무엇인지 이해하려고 합니다.이 코드는 동작하지만, 접속수가 계속 증가하는 것 같아서 좋지 않다고 생각합니다만, 가르쳐 주실 수 있을까요?
mysql 서버를 새로 시작했을 때(앱을 실행하지 않고) 연결은 이미 60개였는데, 그게 뭐죠?
MariaDB [(none)]> show status like 'Conn%';
+-----------------------------------+-------+
| Variable_name | Value |
+-----------------------------------+-------+
| Connection_errors_accept | 0 |
| Connection_errors_internal | 0 |
| Connection_errors_max_connections | 0 |
| Connection_errors_peer_address | 0 |
| Connection_errors_select | 0 |
| Connection_errors_tcpwrap | 0 |
| Connections | 60 |
+-----------------------------------+-------+
7 rows in set (0.001 sec)
그 후 응용 프로그램을 실행하면 연결 수가 64개로 늘어납니다.
MariaDB [(none)]> show status like 'Conn%';
+-----------------------------------+-------+
| Variable_name | Value |
+-----------------------------------+-------+
| Connection_errors_accept | 0 |
| Connection_errors_internal | 0 |
| Connection_errors_max_connections | 0 |
| Connection_errors_peer_address | 0 |
| Connection_errors_select | 0 |
| Connection_errors_tcpwrap | 0 |
| Connections | 64 |
+-----------------------------------+-------+
7 rows in set (0.000 sec)
백엔드 어플리케이션을 재부팅하거나 프론트엔드에서 요청을 할 때마다 접속 수가 증가하는 것 같습니다.
접속을 관리하는 방법을 잘 모르기 때문에 사용하고 있는 코드의 일부(리액션, 표현, 노드 등)가 명확하지 않은 것은 인정합니다.잠시만 기다려 주십시오.
이것은 제가 사용하고 있는 코드의 일부입니다.최적의 접속 관리 방법을 찾는 데 도움이 되었으면 합니다.
그 이후로는connection
응용 프로그램의 여러 영역에서 사용됩니다.다음 내용이 포함된 .js 파일을 만듭니다.
class Connection {
static connect() {
var mysql = require('mysql');
var connection = null;
var connection_settings = {
host : 'localhost',
database : '..',
user : '..',
password : '..',
}
connection = mysql.createConnection(connection_settings);
connection.connect(function(err) {
if(err) {
console.log('error when connecting to db:', err);
}
});
return connection;
}
}
module.exports = { Connection }
그런 다음 db를 쿼리하는 코드가 포함된 파일:
const { Connection } = require('../database.js')
function openLessonSections (lessonID, connection){
return new Promise(function (resolve, reject){
const sql = "SELECT * FROM sections WHERE lesson_id=" + lessonID;
connection.query (sql, function (error, result){
console.log('Loading lesson "' + lessonID + '".');
if (error) reject (error);
resolve (result);
});
});
}
async function openLesson(lessonID, connection){
return await openLessonSections(lessonID, connection);
}
exports.lessonOpen = function(req, res, next) {
const connection = Connection.connect();
console.log('request received');
const lessonID = JSON.parse(req.body.lessonID);
console.log('Opening lesson: ' + lessonID);
openLesson(lessonID, connection)
.then(function(result){
console.log('The lesson was opened successfully.');
res.status(200).json({sections: result});
})
.catch(function (error){
res.status(500).json(error);
console.log('There was an error while opening the lesson. ' + error);
});
connection.end();
}
내가 뭔가 잘못하고 있다는 것을 알고 있고 최선의 방법이 무엇인지 약간 혼란스럽다.
한 가지 옵션은 연결 풀을 만드는 것입니다(한 번).
const mysql = require('mysql');
const pool = mysql.createPool({
host: 'myhost',
user: 'myuser',
password: 'mypass',
database: 'mydb',
connectionLimit: 10,
supportBigNumbers: true
})
그런 다음 쿼리가 있을 때마다 풀에서 연결을 가져옵니다.
function query(sql, args) {
return new Promise((resolve, reject) => {
pool.getConnection(function(err, connection) {
if (err) {
return reject(err);
}
connection.query(sql, args, function(err, result) {
connection.release();
if (err) {
return reject(err);
}
return resolve(result);
});
});
});
}
주의: 이 예는 (콜백 형식의 코드가 아닌) 약속 형식의 코드로 정리되어 있습니다.
내보내기query
기능:
module.exports = {
query
};
위의 모든 코드(예: db.js)를 모듈에 넣고 다음과 같이 사용합니다.
const { query } = require('db.js');
const sql = 'SELECT * FROM table';
query(sql).then(result => {
// Do something with result
})
잘못 짚었어요.
그STATUS
Connections
는 서버(mysqld)가 기동했을 때 제로에서 시작하는 카운터입니다. Connections/Uptime
1초당 1개 또는 1시간당 1개 정도일 수 있습니다.본 적이 있다Connections
10억이 넘었지만 서버는 몇 주 동안 가동되고 있었습니다.
한편, 「접속 풀링」의 형태도 있습니다만, 스택내의 몇개의 컴포넌트에 의해서 도입될 가능성이 있습니다.
데이터베이스 접속을 처리하는 가장 좋은 방법이 무엇인지 이해하려고 합니다.
간단한 대답은 "걱정하지 마세요"입니다.
1개의 웹 페이지(대부분의 경우)에는 1개의 MySQL/MariaDB 연결이 필요합니다.하나의 웹 페이지를 구축하기 위해 코드가 여러 번 연결되어 있으면 비효율적입니다.다양한 JS 컴포넌트를 통해 왔다 갔다 하는 것 같습니다.아마 '상태'가 저장되지 않았기 때문에 별도의 접속을 해야 할 수도 있습니다."데이터 흐름"의 도표를 그립니다(또는 목록을 만듭니다).너무 많이 왔다 갔다 하는 것은 좋지 않다.일반 웹 페이지는 하나의 연결을 가지며 전체 페이지를 작성한 후 사라집니다.그러나 JS와 AJAX에서는 상호 작용이 필요한 경우를 제외하고 앞뒤로 저항하는 것이 매력적입니다.
언급URL : https://stackoverflow.com/questions/56513480/nodejs-expressjs-proper-way-to-manage-connection-to-mysql-db
'programing' 카테고리의 다른 글
문자 목록을 문자열로 변환 (0) | 2022.09.23 |
---|---|
PHP와 함께 comet을 사용하시겠습니까? (0) | 2022.09.23 |
MySQL "wait_timeout"이 긴 쿼리에 적용되지 않습니까? (0) | 2022.09.23 |
정수 불변 (0) | 2022.09.23 |
1개의 패스로 여러 개의 키가 입력되어 있는지 확인하려면 어떻게 해야 합니까? (0) | 2022.09.23 |