mysql-pool.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. };
  37. var client = {
  38. pools: [],
  39. /**
  40. * 得到一个数据库连接
  41. * @param name 数据库pool名字name
  42. * @return {*}
  43. */
  44. getConnection: function(name){
  45. var pool = this.pools[name];
  46. return pool ? pool.getConnection() : null;
  47. },
  48. /**
  49. * 释放一个数据库连接
  50. * @param name 数据库pool名字name
  51. * @param con 连接
  52. */
  53. freeConnection: function(name,con){
  54. var pool = this.pools[name];
  55. if(pool){
  56. pool.freeConnection(con);
  57. }
  58. },
  59. /**
  60. * 释放一个数据库所有连接
  61. * @param name 数据库pool名字name
  62. */
  63. freePool: function(name){
  64. var pool = this.pools[name];
  65. if(pool)
  66. pool.freeAll();
  67. },
  68. /**
  69. * 释放所有数据库的所有连接
  70. */
  71. freeAll: function(){
  72. for(var key in this.pools)
  73. this.pools[key].freeAll();
  74. }
  75. };
  76. exports.instance = function(config){
  77. // if(client.pools.length < 1){
  78. // for(var i = 0; i < config.length; i++){
  79. client.pools[config.pool.name] = new pool(config);
  80. // }
  81. // }
  82. return client;
  83. };