azure 连接丢失时如何重新连接SQL Server繁琐

uemypmqf  于 2022-11-17  发布在  SQL Server
关注(0)|答案(2)|浏览(163)

js and using tedious to connect. Connection is successful and I'm able to connect. However in period of time I would lose connect and receive these errors in Azure.
RequestError: Requests can only be made in the LoggedIn state, not the Final stateat RequestError (D:\home\site\wwwroot\node_modules\tedious\lib\errors.js:32:12)
at Connection.makeRequest (D:\home\site\wwwroot\node_modules\tedious\lib\connection.js:2380:49)at Connection.execSql (D:\home\site\wwwroot\node_modules\tedious\lib\connection.js:2034:10)at submitCode (D:\home\site\wwwroot\controller\mssqlController.js:121:16)at Layer.handle [as handle_request] (D:\home\site\wwwroot\node_modules\express\lib\router\layer.js:95:5)at next (D:\home\site\wwwroot\node_modules\express\lib\router\route.js:137:13)at Route.dispatch (D:\home\site\wwwroot\node_modules\express\lib\router\route.js:112:3)at Layer.handle [as handle_request] (D:\home\site\wwwroot\node_modules\express\lib\router\layer.js:95:5)at D:\home\site\wwwroot\node_modules\express\lib\router\index.js:281:22at Function.process_params (D:\home\site\wwwroot\node_modules\express\lib\router\index.js:335:12) {code: 'EINVALIDSTATE'}[0mPOST /login [32m200 [0m11.820 ms - 27[0m
Here is my code:

let config = {
    server: '',
    authentication: {
        type: 'default',
        options: {
            userName: '',
            password: ''
        }
    },
    options: {
        // If you are on Microsoft Azure, you need encryption:
        encrypt: true,
        database: ''
    }
};

let connection = new Connection(config);
connection.on('connect', function (err) {
    // If no error, then good to proceed.  
    console.log("err", err);
});

let Request = require('tedious').Request
let TYPES = require('tedious').TYPES;

My question is where and what can I add to reconnect or reset SQL Server in Azure if connection is lost?

elcex8rz

elcex8rz1#

您可以尝试使用以下代码重试连接:

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();
  });
}

一旦建立了初始连接,但在此期间连接丢失,则连接池将自动获取连接并处理您的连接。

omtl5h9j

omtl5h9j2#

我建议使用mssql节点包,它仍然使用冗长的代码,并使用pool--它将自动重新连接。
https://www.npmjs.com/package/mssql#connections-1
否则,您可以查找connection.on('end')事件或error事件,然后编写一个自定义函数来重试连接。https://github.com/tediousjs/tedious/blob/master/examples/simple-client.js

相关问题