node mysql 连接池 超时_node-mssql使用连接池连接超时时如何取消自动重连

本文探讨了在使用Node.js的mssql模块进行数据库操作时遇到连接池连接超时的问题。当连接超时,如何配置以避免无限重试并直接返回错误。通过设置`connectionTimeout`和`requestTimeout`属性可以限制连接和请求的超时时间,而`idleTimeoutMillis`可控制未使用连接的关闭。在实际操作中,即使SQL服务器关闭,查询仍然会尝试重新连接,寻求解决方案以确保超时后立即返回错误。
摘要由CSDN通过智能技术生成

题目描述

连接池连接成功后,执行数据库操作时连接超时,如何配置才能直接返回错误,而不是一直在尝试重新连接

相关代码

const to = require('await-to-js').default;

const sql = require('mssql');

const timeOut = require('../utils/timeOut');

const config = {

user: 'sa',

password: '123',

server: '127.0.0.1',

database: 'test',

port: 1433,

appName: 'node-test',

connectionTimeout: 5000, //连接timeout,单位ms 默认 15000

requestTimeout: 5000,//请求timeout,单位ms默认15000

//parseJSON: true, //将json数据集转化成json obj

options: {

encrypt: false // 是否加密连接,如果在Windows Azure上使用,设置为true

},

pool: {

max: 100,

min: 0,

idleTimeoutMillis: 30000 //设置关闭未使用连接的时间,单位ms默认30000

}

};

(async () => {

let err, pool, result;

for (; ;) {

[err, pool] = await to(new sql.ConnectionPool(config).connect());

if (!err) {

pool.on('error', err => {

console.error(err.message);

});

console.log(`数据库连接成功!`);

console.log(`SQL服务器地址:${config.server}`);

break;

} else if (pool !== undefined) {

pool.close();

}

console.error(err.message);

console.error(`数据库连接失败,5秒后重新连接...`);

await timeOut(config.connectionTimeout);

}

// 此时将SQL Server服务关闭,下面的查询连接超时不会立即返回错误,而是一直在尝试重新连接,如何配置才能直接返回错误

await timeOut(15000);

[err, result] = await to(pool.query`SELECT 1`);

// 需要超时后直接返回错误

console.log(err, result);

})();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值