-
Error / mysql connection-Pool DB연결 끊김 timeoutWeb dev/Error 2022. 5. 7. 23:12728x90반응형
express로 서버를 구현하였다. AWS RDS로 디비를 구축하여 mysql로 연결을 하였는데 자꾸 끊김현상이 발생되었다.
mysql은 오랜시간 사용하지 않으면 자동으로 끊기게 된다.
검색해보면 timeout설정을 바꾸라고 하던데 설정을 바꾸지 않고 connection-Pool을 사용하면된다.
커넥션풀은 WAS가 실행되면 DB에 바로연결하지 않고 중간에서 커넥션풀이 커넥션을 빌려주고 반납받아
DB에 연결과부하가 되지 않도록 관리 해준다. 설정으로 커넥션수도 제한할 수 있다.
db.js
const dotenv = require('dotenv'); dotenv.config(); const mysql = require("mysql"); const pool = mysql.createPool({ host: process.env.DB_HOST, user: process.env.DB_USER, password: process.env.DB_PSWORD, database: process.env.DB_DATABASE, }) const db = (callback) => { pool.getConnection((err,conn) => { if(!err){ console.log("모듈 연결성공") callback(conn) }else{ console.log("모듈 연결실패") console.log(err); } }); } // 처음 썼던 코드 // const db = mysql.createConnection({ // host: process.env.DB_HOST, // user: process.env.DB_USER, // password: process.env.DB_PSWORD, // database: process.env.DB_DATABASE, // }); module.exports = db;
register.js
const express = require('express'); const router = express.Router(); const db = require('../config/db'); router.post('/register', (req, res) => { const id = req.query.id const name = req.query.name const password = req.query.password const sql1 = "INSERT INTO users(id,name,password) VALUES(?,?,?);"; const params = [id, name, password] db((conn) => { conn.query(sql1, params, (err) => { console.log("쿼리시작") if(!err) { console.log("가입성공") res.send({success: true}) } else { res.send({err:"동일한 아이디가 있습니다."}) console.log("동일한 아이디가 있습니다.") } }) conn.release(); }); }); module.exports = router;
connection-pool을 사용하면 반드시 release()를 실행하여 커넥션을 반납해주어야 한다.
728x90반응형'Web dev > Error' 카테고리의 다른 글