What is the stable way to connect mariadb in Node.js?

Asked 2 years ago, Updated 2 years ago, 134 views

We are developing a website with node.js + express environment.

After developing the division part using sequelize, I was familiar with sql, so I removed all the sequelize parts and developed them.

However, the database connection keeps disconnecting.

As far as I'm concerned,

The degree comes to mind.

Alternatively, http://berr.tistory.com/222 introduces you to add a listener whose connection is broken.

If I clean up, the db connection keeps disconnecting, so I want to solve this problem. I wonder how to develop it in practice.

node.js mariadb express

2022-09-22 10:40

1 Answers

I don't know how to manage it at a commercial serviceable level.

The node.js module has something called 'generic-pool'.

Since it is a module that manages the connection pool, I think the problem of disconnection will be solved.

Mysql example.

db_pooling.js

var generic_pool    = require("generic-pool");
var mysql       = require("mysql");

// // local env
config = {
    host:'127.0.0.1',
    user:'username',
    password:'password',
    database:'databasename'
};

var pooling     = generic_pool.Pool({
    name:"mysql",
    create:function(cb){
        var conn = mysql.createConnection(config);
        conn.connect(function(err){
            if(err) console.log ("mysql connection error");
            else {
            //  console.log ("mysql connection successful");
            }   }   cb(err, conn);
            // Throw connection object into pooling via callback function
        });
    },
    destroy:function(myConn){
        myConn.end(function(err){
            if(err) console.log ("mysql disconnect error");
    //      else console.log ("mysql disconnect succeeded");
        });
    },
    min:1,
    max:2,
    idleTimeoutMillis:1000*500,
    log:false

});

process.on("exit", function(){
    pooling.drain(function(){
        pooling.destroyAllNow();
    });
});

module.exports = pooling;

When using pool,

query_processing.js

var pool = require("./db_pooling");

exports.search = function(cb, param){ // param = request.params
//console.log(param);
    pool.acquire(function(err, conn){
        if (err) console.log ("connection acquisition failed" + err);
        else
        {
            conn.query(
                "SELECT * FROM TBL WHERE id=? LIMIT 1",
                [param.id],
                function(err, result){
                    if(err) console.log(err);
                    else    console.log(result);
                    pool.release(conn);
                    cb(err, result);
                }
            );
        }   
    });
}

You can write it like this.


2022-09-22 10:40

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.