mysql-pool.js 2.5 KB

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