完善serverless部署环境
This commit is contained in:
57
server/db.js
57
server/db.js
@@ -1,37 +1,70 @@
|
||||
const mysql = require('mysql2/promise');
|
||||
|
||||
let pool;
|
||||
const IS_SERVERLESS = [
|
||||
process.env.SERVERLESS,
|
||||
process.env.VERCEL,
|
||||
process.env.AWS_LAMBDA_FUNCTION_NAME,
|
||||
process.env.NETLIFY,
|
||||
process.env.FUNCTION_TARGET,
|
||||
process.env.K_SERVICE
|
||||
].some(Boolean);
|
||||
|
||||
function initPool() {
|
||||
if (pool) {
|
||||
pool.end().catch(e => console.error('Error closing pool:', e));
|
||||
function getConnectionLimit() {
|
||||
const parsed = parseInt(process.env.MYSQL_CONNECTION_LIMIT, 10);
|
||||
if (!Number.isNaN(parsed) && parsed > 0) {
|
||||
return parsed;
|
||||
}
|
||||
pool = mysql.createPool({
|
||||
return IS_SERVERLESS ? 2 : 10;
|
||||
}
|
||||
|
||||
function createPool() {
|
||||
return mysql.createPool({
|
||||
host: process.env.MYSQL_HOST || 'localhost',
|
||||
port: parseInt(process.env.MYSQL_PORT) || 3306,
|
||||
port: parseInt(process.env.MYSQL_PORT, 10) || 3306,
|
||||
user: process.env.MYSQL_USER || 'root',
|
||||
password: process.env.MYSQL_PASSWORD || '',
|
||||
database: process.env.MYSQL_DATABASE || 'display_wall',
|
||||
waitForConnections: true,
|
||||
connectionLimit: 10,
|
||||
queueLimit: 0
|
||||
connectionLimit: getConnectionLimit(),
|
||||
queueLimit: 0,
|
||||
enableKeepAlive: true,
|
||||
keepAliveInitialDelay: 0
|
||||
});
|
||||
}
|
||||
|
||||
function getPool() {
|
||||
if (!pool) {
|
||||
pool = createPool();
|
||||
}
|
||||
return pool;
|
||||
}
|
||||
|
||||
function initPool({ force = false } = {}) {
|
||||
if (pool && !force) {
|
||||
return pool;
|
||||
}
|
||||
|
||||
if (pool) {
|
||||
pool.end().catch(e => console.error('Error closing pool:', e));
|
||||
}
|
||||
|
||||
pool = createPool();
|
||||
return pool;
|
||||
}
|
||||
|
||||
async function checkHealth() {
|
||||
try {
|
||||
if (!pool) return { status: 'down', error: 'Database pool not initialized' };
|
||||
await pool.query('SELECT 1');
|
||||
await getPool().query('SELECT 1');
|
||||
return { status: 'up' };
|
||||
} catch (err) {
|
||||
return { status: 'down', error: err.message };
|
||||
}
|
||||
}
|
||||
|
||||
initPool();
|
||||
|
||||
module.exports = {
|
||||
query: (...args) => pool.query(...args),
|
||||
query: (...args) => getPool().query(...args),
|
||||
getPool,
|
||||
initPool,
|
||||
checkHealth
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user