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

题目描述

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

相关代码

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);
})();
阅读 3.4k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题