node-mysql connection pooling

后端 未结 3 567
天涯浪人
天涯浪人 2020-12-30 06:35

I am using node-mysql module (https://github.com/felixge/node-mysql) OR (http://utahjs.com/2010/09/22/nodejs-and-mysql-introduction/) .

Is this API handling connect

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-30 06:52

    Update: Feb 2013 - pool support has been added to node-mysql, see docs

    Example using built-in pool:

    var pool = require('mysql').createPool(opts);
    
    pool.getConnection(function(err, conn) {
      conn.query('select 1+1', function(err, res) {
        conn.release();
      });
    });
    

    Pre 2013 solutions:

    You can use node-pool or mysql-pool or use your own simple round-robin pool

    function Pool(num_conns)
    {
        this.pool = [];
        for(var i=0; i < num_conns; ++i)
            this.pool.push(createConnection()); // your new Client + auth
        this.last = 0;
    }
    
    Pool.prototype.get = function()
    {
        var cli = this.pool[this.last];
        this.last++;
        if (this.last == this.pool.length) // cyclic increment
           this.last = 0;
        return cli;
    }
    

    now you can hope to have all queries callbacks to execute in 1 second:

    var p = new Pool(16);
    for (var i=0; i < 10; ++i)
    {
        p.get().query('select sleep(1)', function() { console.log('ready'); } ); // server blocks for 1 second
    }
    

提交回复
热议问题