简体   繁体   中英

NodeJS DB2 Connection pooling for Express app

I see very few online posts when it comes to NodeJS with IBM DB2. I am new to NodeJS and having issues to configure connection pooling for my web app. I am successfully running node app with single connection in my local but not sure how to configure connection pooling. Below code is how I have it for single connection.

DBConnection JS:

module.exports = function(dbConnection)
{
 var Pool = require('ibm_db').Pool;
 var pool = new Pool();

 pool.open("MY_CONNECTION_STRING",function(err,connection){

  //error handling logic ...

  dbConnection(connection);
 });
}

App listener js:

var express = require('express');
var app = express();

app.listen(8080,function(){
 console.log("server started..);
});

require('./DBConnection')(function(connection){

  app.get('/getEmpId',function(req,res){
   connection.query("MY_SQL_QUERY",function(error,results,fields){
    //some other logic

    res.send(results[0]);   

    //Closing connection     
    connection.close(function(err2) {
        if(err2) console.log(err2);
    });
   });
  });      
}

Need your suggestions to setup connection pool where I can use one connection for each request when concurrent users are accessing and close the connection after serving request.

You can take a look at the brief samples provided with the IBM node-ibm_db driver . It has a section on Connection Pooling . The driver reuses the node-odbc pool and you need to invoke the open/close calls on the Pool object. Here is the sample taken from the node-ibm_db site:

var Pool = require("ibm_db").Pool
    , pool = new Pool()
    , cn = "DATABASE=dbname;HOSTNAME=hostname;PORT=port;PROTOCOL=TCPIP;UID=dbuser;PWD=xxx";

pool.open(cn, function (err, db) {
    if (err) {
        return console.log(err);
    }

    //db is now an open database connection and can be used like normal
    //if we run some queries with db.query(...) and then call db.close();
    //a connection to `cn` will be re-opened silently behind the scense
    //and will be ready the next time we do `pool.open(cn)`
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM