如果断开连接,则拾取连接

Pick up connection if there is a disconnect

我使用这个特定版本:SQL 服务器 npm 包的 https://github.com/patriksimek/node-mssql/tree/v3.3.0#multiple-connections

我一直在翻阅 Tedious(底层库)的文档和 Microsoft 的文档(参见上面的 github link)。

我找不到像 getCurrentConnectiongetConnectionStatus 或类似的东西那样简单的东西。

我有两种方法可以解决这个问题,但我对这两种方法都不满意,所以这就是我在这里问的原因。

我的第一个方法是设置超时并让连接函数在每个 catch(err).

上调用自身

第二个是在中间件中处理这个问题,但如果一切正常,它将在每个请求上建立到 SQL 的连接并再次关闭该连接。

我的中间件函数:

api.use(function(err, req, res, next){
   sql.close();
   sql.connect(config.database).then(() => {
     next();
   }).catch(function(err) {
     sql.close();
     server.main();
   });
});

我想,如果可能的话,在服务器或数据库崩溃时选择连接而不是关闭并启动一个新连接我仍然有一些来自现有功能的数据。

如果我没有理解错的话,您基本上是想重用连接。 Tedious 具有内置的连接池,因此您不必担心重复使用它们:

var config = {
    user: '...',
    password: '...',
    server: 'localhost',
    database: '...',
    pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
    }
}

在上面的示例中(刚从您发布的 GitHub URL 复制而来),池中将有 10 个连接可供使用。妙处在于:池管理器将为您处理所有连接的使用和重用,即连接数量根据您的应用程序的需要是灵活的。

如您所述,数据库崩溃怎么办?这也是内置的:connection health-check:

Internally, each Connection instance is a separate pool of TDS connections. Once you create a new Request/Transaction/Prepared Statement, a new TDS connection is acquired from the pool and reserved for desired action. Once the action is complete, connection is released back to the pool. Connection health check is built-in so once the dead connection is discovered, it is immediately replaced with a new one.

希望对您有所帮助!

在 Arnold 的帮助下,我了解了 mssql 包并且它的内部工作原理好多了。

因此,我想出了以下解决问题的方法。

let intervalFunction;
const INTERVAL_DURATION = 4000;

if (require.main === module){
    console.log("Listening on http://localhost:" + config.port + " ...");
    app.listen(config.port);
    // try to connect to db and fire main on succes. 
    intervalFunction = setInterval(()=> getConnection(), INTERVAL_DURATION);
}

function getConnection() {
  sql.close();
  sql.connect(config.database).then(() => {
    sql.close();
    clearInterval(intervalFunction);
    main();
}).catch(function(err) {
    console.error(err);
    console.log(`DB connection will be tried again in ${INTERVAL_DURATION}ms`)
    sql.close();
  });
}

一旦建立初始连接但同时丢失,池将自动获取连接并处理您的连接