node.js池操作

来源:互联网 发布:台湾也用淘宝吗 编辑:程序博客网 时间:2024/05/29 02:44

对于池的注意是是从优化数据库开始的, 对数据库建立连接池。其实这种系统资源,都是应该建立成池的形式,然后从池中获取,而不是每次使用再向系统申请。这种处理方式,相当于利用空间来换取时间。预先开辟好系统所需要的资源,然后在内存里操作。


node.js的池可以理解为对于对象创建的抽象,下面用一个例子来说明这点


var Pool = require('generic-pool').Pool;function Person(){this.name = 'person';console.log('<Person struct...>');this.end = function () {console.log('<func end...>');}this.say = function () {console.log('<Person func say...>');}}var pool = new Pool({    name     : 'person',    create   : function(callback) {        var c = new Person();        // parameter order: err, resource        callback(null, c);    },    destroy  : function(client) { client.end(); },    max      : 10,    min      : 4,    idleTimeoutMillis : 30000,    log : false});pool.acquire(function(err, client) {   if (err) {    } else {    console.log('acquire one');        client.say();    }    pool.release(client);});pool.acquire(function(err, client) {    if (err) {    } else {        console.log('acquire two');        client.say();    }    pool.release(client);});pool.acquire(function(err, client) {    if (err) {    } else {        console.log('acquire three');        client.say();    }    pool.release(client);});pool.drain(function() {    pool.destroyAllNow();});


0 0