mysql-pool.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /**
  2. */
  3. var Mysql = require('mysql');
  4. var pool = function(config){
  5. this.free = [];//空闲连接集合
  6. this.used = 0; //已使用连接集合
  7. for(var key in config.pool){this[key] = config.pool[key];}
  8. this.newConnection = function(){
  9. var con = Mysql.createConnection(config.db);
  10. return con;
  11. };
  12. this.getConnection = function(){
  13. var con = null;
  14. if(this.used < this.maxconn){
  15. if(this.free.length > 0){
  16. con = this.free.shift();
  17. }else{
  18. con = this.newConnection();
  19. }
  20. this.used++;
  21. // console.log('当前使用连接: ' + this.used + ' 空闲连接: ' + this.free.length);
  22. }
  23. return con;
  24. };
  25. this.freeConnection = function(con){
  26. this.free.push(con);
  27. this.used--;
  28. };
  29. this.freeAll = function(){
  30. this.used = 0;
  31. for(var i = 0; i < this.free.length; i++){
  32. this.free[i].end();
  33. }
  34. this.free = [];
  35. };
  36. this.endConnection = function(){
  37. this.freeAll();
  38. // for(var i = 0; i < this.free.length; i++){
  39. // this.free[i].end();
  40. // }
  41. }
  42. };
  43. var client = {
  44. pools: [],
  45. /**
  46. * 得到一个数据库连接
  47. * @param name 数据库pool名字name
  48. * @return {*}
  49. */
  50. getConnection: function(name){
  51. var pool = this.pools[name];
  52. return pool ? pool.getConnection() : null;
  53. },
  54. /**
  55. * 释放一个数据库连接
  56. * @param name 数据库pool名字name
  57. * @param con 连接
  58. */
  59. freeConnection: function(name,con){
  60. var pool = this.pools[name];
  61. if(pool){
  62. pool.freeConnection(con);
  63. }
  64. },
  65. /**
  66. * 释放一个数据库所有连接
  67. * @param name 数据库pool名字name
  68. */
  69. freePool: function(name){
  70. var pool = this.pools[name];
  71. if(pool)
  72. pool.freeAll();
  73. },
  74. /**
  75. * 释放所有数据库的所有连接
  76. */
  77. freeAll: function(){
  78. for(var key in this.pools)
  79. this.pools[key].freeAll();
  80. },
  81. end:function(){
  82. for(var key in this.pools)
  83. this.pools[key].freeAll();
  84. }
  85. };
  86. exports.instance = function(config){
  87. // if(client.pools.length < 1){
  88. // for(var i = 0; i < config.length; i++){
  89. client.pools[config.pool.name] = new pool(config);
  90. // }
  91. // }
  92. return client;
  93. };