当前位置: 首页 > 知识库问答 >
问题:

当第一次连接失败时,如何在Node.js中重试数据库连接?

景成和
2023-03-14

我正在使用SQL服务器与Node.js.当连接首次尝试失败时,Node.js不会重新尝试连接。我正在使用setTimeout()定期尝试,直到它连接。

const poolPromise = new sql.ConnectionPool(config.db);
poolPromise
  .connect()
  .then(pool => {
    console.log('Connected to MSSQL');
    return pool;
  })
  .catch(err => {
    if (err && err.message.match(/Failed to connect to /)) {
      console.log(new Date(), String(err));

      // Wait for a bit, then try to connect again
      setTimeout(function() {
        console.log('Retrying first connect...');
        poolPromise.connect().catch(() => {});
      }, 5000);
    } else {
      console.error(new Date(), String(err.message));
    }
  });

上面的代码尝试连接,失败并尝试第二次,但不会继续第三次、第四次等。

共有2个答案

易成天
2023-03-14

在检查了这里的答案后,我同意回电是一种方式。我编写了以下脚本,试图连接到MySQL,直到连接建立,然后偶尔检查连接是否仍然有效,如果无效,请再次尝试连接。我放置了控制台。日志在一些地方,这样当事情运行时,你可以看到并理解正在发生的事情。

var mysql = require('mysql');
var env = require('dotenv').config()

// ENVIRONMENT LOADS
var env = process.env.NODE_ENV.trim();
var host = process.env.MYSQL_HOST.trim();
var user = process.env.MYSQL_USER.trim();
var password = process.env.MYSQL_ROOT_PASSWORD.trim();
var database = process.env.MYSQL_DB.trim();
var port = process.env.MYSQL_PORT.trim();

console.log('\n\n********\n\nMySQL Credentials\n\n********\n\n');
if (env != 'production') {
  console.log("Host: ", host, ":", port);
  console.log("User: ", user);
  console.log("Database: ", database);
  console.log("Password: ", password);
}else{
  console.log('Using Production Credentials');  
}
console.log('\n\n************************\n\n');

let mysqlDB = null; // db handler
let connected = null; // default null / boolean
let connectFreq = 1000; // When database is disconnected, how often to attempt reconnect? Miliseconds
let testFreq = 5000; // After database is connected, how often to test connection is still good? Miliseconds

function attemptMySQLConnection(callback) {
  console.log('attemptMySQLConnection')
  if (host && user && database) {

    mysqlDB = mysql.createPool({
      host: host,
      port: port, // Modified for Dev env
      user: user,
      password: password,
      database: database,
      connectionLimit: 300,
      waitForConnections: true, // Default value.
      queueLimit: 300, // Unlimited
      acquireTimeout: 60000,
      timeout: 60000,
      debug: false
    });

    testConnection((result) => {
      callback(result)
    })

  } else {
    console.error('Check env variables: MYSQL_HOST, MYSQL_USER & MYSQL_DB')
    callback(false)
  }
}

function testConnection(cb) {
  console.log('testConnection')
  mysqlDB.query('SELECT 1 + 1 AS solution', (error, results, fields) => {
    try {
      if (error) {
        throw new Error('No DB Connection');
      } else {
        if (results[0].solution) {
          cb(true)
        } else {
          cb(false)
        }
      }
    } catch (e) {
      // console.error(e.name + ': ' + e.message);
      cb(false)
    }
  });
}

function callbackCheckLogic(res) {
  if (res) {
    console.log('Connect was good. Scheduling next test for ', testFreq, 'ms')
    setTimeout(testConnectionCB, testFreq);
  } else {
    console.log('Connection was bad. Scheduling connection attempt for ', connectFreq, 'ms')
    setTimeout(connectMySQL, connectFreq);
  }
}

function testConnectionCB() {
  testConnection((result) => {
    callbackCheckLogic(result);
  })
}

function connectMySQL() {
  attemptMySQLConnection(result => {
    callbackCheckLogic(result);
  });
}

connectMySQL(); // Start the process by calling this once

module.exports = mysqlDB;
郑哲彦
2023-03-14

我写了这个有效的小片段。我将连接部分包装到一个函数中,然后使用递归函数调用它。

在这个例子中,你会看到一个无穷大。

function sql() {
    this.connect = function() {
        return new Promise((resolve, reject) => reject("error connecting"));
    }
}


function connect() {
    return new Promise((resolve, reject) => {
        // const poolPromise = new sql.ConnectionPool("config.db");
        const poolPromise = new sql();
        poolPromise
            .connect()
            .then(pool => {
                console.log("connected");
                resolve(pool);
            })
            .catch(err => {
                console.error(err);
                reject(err);
            });
    });
}

function establishConnection() {
     var a = connect();
     a.then(a => console.log("success"))
    .catch(err => {
        console.error("Retrying");
        // I suggest using some variable to avoid the infinite loop.
        setTimeout(establishConnection, 2000);
    });
};

establishConnection();
 类似资料:
  • 我在MySQL上有2个数据库。ge和GE_SC001。 我可以通过我的ASP.NET mvc应用程序在本地访问这两个。 Web.config null 稍后,当我在web服务器上部署应用程序,并尝试从本地机器访问它们时。我将server=localhost更改为机器的面向外部的IP地址。现在我只能访问一个GE。当我尝试访问第二个时,它会给我错误。 拒绝用户“root”@“对数据库”GE_SC001

  • 问题内容: 通过Node MongoDB本机驱动程序使用Nodejs和MongoDB。需要检索一些文档,并进行修改,然后将其保存回来。这是一个例子: 具有异步性质,如果更新文档的过程花费更长的时间,则当光标到达文档末尾时,数据库连接将关闭。并非所有更新都保存到数据库。 如果省略,则所有文档均正确更新,但应用程序挂起,永不退出。 我看到一则帖子建议使用计数器跟踪更新次数,当回落到零时,然后关闭数据库

  • 我是拉威尔的新手,目前正在拉威尔的一个项目中工作。 当我在我的文件中使用'php工匠服务'来检查它是否工作/localhost,我得到了这个错误: (1/1)HttpException数据库连接失败! 在应用中。php第1014行 应用时- 在ScriptMint中中止时('399','数据库连接失败!')。php第31行 在ScriptMint- 在管道上- at XSP保护- 在管道上- 在T

  • 我们有一个Java应用程序,它使用Quartz来调度作业。我们使用的quartz版本是:Quartz-2.2.1 quartz配置使用JDBC作业存储。 如果在quartz scheduler对象上调用start方法时数据库连接关闭(由于断断续续的网络故障),它将以以下异常失败: 为了确保quartz scheduler成功启动,我们在代码中添加了重试,它在每1秒后调用quartz schedul

  • 我试图连接到我的mongo数据库在我的远程服务器: 但我有一个错误: MongoDB外壳版本:2.6.10连接到:xxx。xxx。xxx。xx:27017/测试2016-11-07T05:18:39.140 0000警告:无法连接到xxx。xxx。xxx。xx:27017,原因:错误号:111连接被拒绝2016-11-07T05:18:39.142 0000错误:无法连接到服务器xxx。xxx。x