Last active
August 5, 2022 21:07
-
-
Save mrunderline/90fb122bb584c9b79c4701200cde9e3b to your computer and use it in GitHub Desktop.
simple node js cluster with mysql connections
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const cluster = require('cluster'); | |
const mysql = require('mysql'); | |
const numCPUs = require('os').cpus().length; | |
const app = express(); | |
const PORT = 3000; | |
const pool = mysql.createPool({ | |
host: process.env.MYSQL_HOST || 'localhost', | |
port: process.env.MYSQL_PORT || 3306, | |
user: process.env.MYSQL_USER, | |
password: process.env.MYSQL_PASS, | |
database: process.env.MYSQL_DB, | |
connectionLimit: process.env.MYSQL_CONN_LIMIT || numCPUs, | |
}); | |
if (cluster.isMaster) { | |
console.log(`Master ${process.pid} is running`); | |
for (let i = 0; i < numCPUs; i++) { | |
cluster.fork(); | |
} | |
cluster.on('exit', (worker, code, signal) => { | |
console.log(`worker ${worker.process.pid} died`); | |
}); | |
} else { | |
app.listen(PORT, err => { | |
err ? | |
console.log("Error in server setup") : | |
console.log(`Worker ${process.pid} started`); | |
}); | |
app.get('/', (req, res) => { | |
console.log(`Worker process id is ${process.pid}`); | |
pool.query('SELECT 1 + 1 AS solution', function (err, rows, fields) { | |
if (err) throw err; | |
res | |
.status(200) | |
.send(`The solution is: ${rows[0].solution}`); | |
}); | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment