mysql-pool.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /**
  2. * Created with JetBrains WebStorm.
  3. * User: Gary
  4. * Date: 12-11-30
  5. * Time: 上午10:38
  6. * To change this template use File | Settings | File Templates.
  7. */
  8. var Mysql = require('mysql');
  9. // var config = MysqlConfig;
  10. var pool = function(config){
  11. this.free = [];//空闲连接集合
  12. this.used = 0; //已使用连接集合
  13. for(var key in config.pool)
  14. this[key] = config.pool[key];
  15. this.newConnection = function(){
  16. var con = Mysql.createConnection(config.db);
  17. this.free.push(con);
  18. return con;
  19. };
  20. this.getConnection = function(){
  21. var con = null;
  22. if(this.used < this.maxconn){
  23. if(this.free.length > 0){
  24. con = this.free[0];
  25. this.free.splice(0,1);
  26. if(!con)
  27. con = this.getConnection();
  28. }else{
  29. con = this.newConnection();
  30. }
  31. this.used++;
  32. // console.log('当前使用连接: ' + this.used + ' 空闲连接: ' + this.free.length);
  33. }
  34. return con;
  35. };
  36. this.freeConnection = function(con){
  37. this.free.push(con);
  38. this.used--;
  39. };
  40. this.freeAll = function(){
  41. this.used = 0;
  42. for(var i = 0; i < this.free.length; i++){
  43. this.free[i].end();
  44. }
  45. this.free = [];
  46. };
  47. };
  48. var client = {
  49. pools: [],
  50. /**
  51. * 得到一个数据库连接
  52. * @param name 数据库pool名字name
  53. * @return {*}
  54. */
  55. getConnection: function(name){
  56. var pool = this.pools[name];
  57. return pool ? pool.getConnection() : null;
  58. },
  59. /**
  60. * 释放一个数据库连接
  61. * @param name 数据库pool名字name
  62. * @param con 连接
  63. */
  64. freeConnection: function(name,con){
  65. var pool = this.pools[name];
  66. if(pool)
  67. pool.freeConnection(con);
  68. },
  69. /**
  70. * 释放一个数据库所有连接
  71. * @param name 数据库pool名字name
  72. */
  73. freePool: function(name){
  74. var pool = this.pools[name];
  75. if(pool)
  76. pool.freeAll();
  77. },
  78. /**
  79. * 释放所有数据库的所有连接
  80. */
  81. freeAll: 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. };