From e844702654832aaa0be40263f5bccfa9134e0753 Mon Sep 17 00:00:00 2001 From: Manjot Singh Date: Tue, 23 Jun 2020 09:24:29 -0700 Subject: [PATCH] Failover db (#186) * Adds failover to database connection #179 --- api/config/index.js | 36 ++++++++++++++++++++++++++++++------ app.js | 10 ++++++++-- 2 files changed, 38 insertions(+), 8 deletions(-) diff --git a/api/config/index.js b/api/config/index.js index 80480b6..916953b 100644 --- a/api/config/index.js +++ b/api/config/index.js @@ -1,11 +1,35 @@ +const metadata = { + user: process.env.DB_USER || 'root', + password: process.env.DB_PASSWORD || 'root', + database: process.env.NODE_ENV === 'development' ? 'khajana_dev_khajana' : 'khajana_khajana', + dateStrings: true, + acquireTimeout: 5000, + connectionLimit: process.env.DB_POOL_SIZE, +}; +const standbyMetadata = { + port: 3306, + minimumIdle: 0, +}; + module.exports = { - mysql: { + mysql0: { + ...metadata, host: process.env.DB_HOST || 'localhost', port: process.env.DB_PORT || 3306, - user: process.env.DB_USER || 'root', - password: process.env.DB_PASSWORD || 'root', - database: process.env.NODE_ENV === 'development' ? 'khajana_dev_khajana' : 'khajana_khajana', - dateStrings: true, - connectionLimit: process.env.DB_POOL_SIZE, + }, + mysql1: { + ...metadata, + ...standbyMetadata, + host: 'db1.khalis.net', + }, + mysql2: { + ...metadata, + ...standbyMetadata, + host: 'db2.khalis.net', + }, + mysql3: { + ...metadata, + ...standbyMetadata, + host: 'db3.khalis.net', }, }; diff --git a/app.js b/app.js index 64ef459..741552a 100644 --- a/app.js +++ b/app.js @@ -2,15 +2,21 @@ const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const cacheControl = require('express-cache-controller'); -const { createPool } = require('mariadb'); +const { createPoolCluster } = require('mariadb'); const config = require('./api/config'); const routes = require('./api/routes'); const app = express(); const port = process.env.NODE_ENV === 'development' ? '3001' : '3000'; -app.locals.pool = createPool(config.mysql); +// database +app.locals.pool = createPoolCluster(); +app.locals.pool.add('local', config.mysql0); +app.locals.pool.add('db1', config.mysql1); +app.locals.pool.add('db2', config.mysql2); +app.locals.pool.add('db3', config.mysql3); +// app app.use(cors()); app.use(cacheControl({ maxAge: 21600 })); app.use(bodyParser.urlencoded({ extended: true }));