colaf.svgColaf
login 

Author: Colaf Date: 2023.01.08 09:24:08
Category: colaf
Subject: DB wait timeout
Content

DB wait_timeout

내 웹 페이지는 maria DB의 내용을 참조하여 server side rendering 을 한다. 근데 maria DB의 wait_timeout은 28800, 즉 8시간으로 되어 있기 때문에 한번 접근하고 8시간 뒤에는 PROTOCOL_CONNECTION_LOST에러가 발생한다. 따라서 에러가 발생할 때마다 재연결을 해야 한다.

그래서 다음과 같이 코드를 작성했다.

function DB(db_config){
  this.connection = mysql.createConnection(db_config);
  this.handleDisconnect = function(){
    console.log('handle disconnection start');
    this.connection.on('error', (err)=>{//③
      console.log('mariadb.js connection.on error');
      console.log('DB name: ', db_config.database);
      console.log('Error message: ', err);
      if(err.code === 'PROTOCOL_CONNECTION_LOST'){
        this.connection = mysql.createConnection(db_config);//②
      }
      else{
        throw err;
      }
    });
  }
}

const db_config_log = {
  host: process.env.host_mariadb,
  port: process.env.port_mariadb,
  user: process.env.ID_mariadb,
  password: process.env.PW_mariadb,
  database: 'log',
  multipleStatements: true
};
const DB_log = new DB(db_config_log); //①
DB_log.handleDisconnect();

exports.db_log = DB_log;//④

①PROTOCOL_CONNECTION_LOST error가 발생할 때마다 재연결을 하기 위해서 이를 담당하는 객체 DB를 만들었다.

②처음에는 이 부분을 만들지 않아서 자꾸 DB에 접근되지 않는 문제가 있었다. 잠깐 생각해보니 error가 발생할 때마다 createConnection을 해줘야 된다는 것을 깨달았다.

③이 부분도 function(err){…}로 돼 있었는데 이렇게 작성하면 내부에 this.connection의 this가 익명함수를 가리키기 때문에 DB객체의 this와 달라지게 되므로 DB의 this.connection이 새로운 mysql연결 객체를 가리킬 수 없게 된다. 따라서 이것은 화살표함수로 바꾸게 되면 this가 DB객체를 의미하게 되므로 이렇게 설정해 주었다. 화살표함수의 this와 스코프를 참고하자.

④기존에는 exports.db_log=DB_log.connection;을 사용해서 connection을 다른 모듈에 전달하였다.고민해보니 handleDisconnect을 할 때마다 connection이 새로운 객체를 가리키게 되지만 exports.db_log는 업데이트가 안되는 문제가 있었다.

그렇기 때문에 exports.db_log=DB_log 로 기술하여 객체 자체(객체의 주소)를 전달하고 객체 내부의 connect를 handleDisconnect가 변경하도록 했다.

 


tag: