123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- var Mysql = require('mysql');
- var pool = function(config){
- this.free = [];
- this.used = 0;
- for(var key in config.pool)
- this[key] = config.pool[key];
- this.newConnection = function(){
- var con = Mysql.createConnection(config.db);
- this.free.push(con);
- return con;
- };
- this.getConnection = function(){
- var con = null;
- if(this.used < this.maxconn){
- if(this.free.length > 0){
- con = this.free[0];
- this.free.splice(0,1);
- if(!con)
- con = this.getConnection();
- }else{
- con = this.newConnection();
- }
- this.used++;
-
- }
- return con;
- };
- this.freeConnection = function(con){
- this.free.push(con);
- this.used--;
- };
- this.freeAll = function(){
- this.used = 0;
- for(var i = 0; i < this.free.length; i++){
- this.free[i].end();
- }
- this.free = [];
- };
- };
- var client = {
- pools: [],
-
- getConnection: function(name){
- var pool = this.pools[name];
- return pool ? pool.getConnection() : null;
- },
-
- freeConnection: function(name,con){
- var pool = this.pools[name];
- if(pool)
- pool.freeConnection(con);
- },
-
- freePool: function(name){
- var pool = this.pools[name];
- if(pool)
- pool.freeAll();
- },
-
- freeAll: function(){
- for(var key in this.pools)
- this.pools[key].freeAll();
- }
- };
- exports.instance = function(config){
- if(client.pools.length < 1){
-
- client.pools[config.pool.name] = new pool(config);
-
- }
- return client;
- };
|