node.js + mysql connection pooling

前端 未结 7 1059
执念已碎
执念已碎 2020-11-28 02:25

I\'m trying to figure out how to structure my application to use MySQL most efficent way. I\'m using node-mysql module. Other threads here suggested to use connection poolin

相关标签:
7条回答
  • 2020-11-28 03:13

    You will find this wrapper usefull :)

    var pool = mysql.createPool(config.db);
    
    exports.connection = {
        query: function () {
            var queryArgs = Array.prototype.slice.call(arguments),
                events = [],
                eventNameIndex = {};
    
            pool.getConnection(function (err, conn) {
                if (err) {
                    if (eventNameIndex.error) {
                        eventNameIndex.error();
                    }
                }
                if (conn) { 
                    var q = conn.query.apply(conn, queryArgs);
                    q.on('end', function () {
                        conn.release();
                    });
    
                    events.forEach(function (args) {
                        q.on.apply(q, args);
                    });
                }
            });
    
            return {
                on: function (eventName, callback) {
                    events.push(Array.prototype.slice.call(arguments));
                    eventNameIndex[eventName] = callback;
                    return this;
                }
            };
        }
    };
    

    Require it, use it like this:

    db.connection.query("SELECT * FROM `table` WHERE `id` = ? ", row_id)
              .on('result', function (row) {
                setData(row);
              })
              .on('error', function (err) {
                callback({error: true, err: err});
              });
    
    0 讨论(0)
提交回复
热议问题