英文:
MariaDB NodeJS backend : too many connections
问题
我有一个使用MariaDB数据库的NodeJS Express后端。
我的文件dbconnect.js创建了一个MariaDB池,并有一个用于执行查询的函数。
const mariadb = require('mariadb');
const pool = mariadb.createPool({
host: process.env.DBHost,
user: process.env.DBUser,
database: process.env.DB,
password: process.env.DBSecret
});
const dbQuery = async(query) => {
let conn;
let res = '';
try {
conn = await pool.getConnection();
res = await conn.query(query);
} catch (err) {
console.log("Error sending Query: ", query, err.text);
} finally {
if (conn) {
conn.end();
}
return res;
}
}
一切似乎都运行得很完美,但在服务器运行几个月后,控制台开始出现以下消息:
这些消息每10-14秒出现一次,但没有执行任何查询。
感谢任何帮助。
英文:
I have a NodeJS express backend which uses a MariaDB database.
My file dbconnect.js creates a mariadb pool and has a function to make queries.
const mariadb = require('mariadb');
const pool = mariadb.createPool({
host: process.env.DBHost,
user: process.env.DBUser,
database: process.env.DB,
password: process.env.DBSecret
});
const dbQuery = async(query) => {
let conn;
let res = '';
try {
conn = await pool.getConnection();
res = await conn.query(query);
} catch (err) {
console.log("Error sending Query: ", query, err.text);
} finally {
if (conn) {
conn.end();
}
return res;
}
}
Everything seems to work perfectly, but after a few months with the server running these messages begin to appear on the console:
These messages keep appearing every 10-14 seconds, but no queries are being performed.
Thanks for any help
答案1
得分: 2
配置你的连接池在特定时间进行ping测试,这样它会在服务器关闭连接之前关闭任何不活动的连接。 mariadb
提供了 pingInterval
用于此功能。
将这段代码替换为你的代码:
const pool = mariadb.createPool({
host: process.env.DBHost,
user: process.env.DBUser,
database: process.env.DB,
password: process.env.DBSecret,
pingInterval: 60000
});
这将每 60秒
向服务器发送一个ping,防止服务器关闭不活动的连接。
英文:
I am not sure but there is one way,
configure your connection pool to ping at particular time. so it will close any inactive connections before the server closes them. mariadb
has pingInterval
for this
Replace this code with your code
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const pool = mariadb.createPool({
host: process.env.DBHost,
user: process.env.DBUser,
database: process.env.DB,
password: process.env.DBSecret,
pingInterval: 60000
});
<!-- end snippet -->
This will send a ping to the server every 60 seconds
, which will prevent the server from closing inactive connections.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论