node.js池操作

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


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();
});



猜你喜欢

转载自blog.csdn.net/adofsauron/article/details/51819532