node-mysql中的连接池代码学习
生活随笔
收集整理的這篇文章主要介紹了
node-mysql中的连接池代码学习
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
node-mysql是一個(gè)node.js下的mysql驅(qū)動(dòng),前段時(shí)間在處理連接池的問題上遇到了連接不釋放的疑難雜癥,雖已解決,但仍需總結(jié)經(jīng)驗(yàn)避免下次重蹈覆轍。下面是node-mysql中的連接池的部分代碼,我加入了詳細(xì)日志,以作備忘之用。
/*** 在連接池中獲取Connection* @param cb* @returns {*}*/ Pool.prototype.getConnection = function (cb) {//本地加的日志console.log("getConnection _allConnections.length: %j, _freeConnections.length: %j", this._allConnections.length, this._freeConnections.length);//池關(guān)閉檢查if (this._closed) {return process.nextTick(function () {return cb(new Error('Pool is closed.'));});}var connection;//檢查可用Connection,大于0直接從池中出棧并返回if (this._freeConnections.length > 0) {connection = this._freeConnections.shift();return process.nextTick(function () {return cb(null, connection);});}//檢查連接數(shù)是否超過上限(默認(rèn)10),沒有超過則創(chuàng)建(真正的CreateConnection)if (this.config.connectionLimit === 0 || this._allConnections.length < this.config.connectionLimit) {connection = new PoolConnection(this, { config: this.config.connectionConfig });//新創(chuàng)建的連接入棧池中this._allConnections.push(connection);//驗(yàn)證新創(chuàng)建的Connection是否可用return connection.connect(function (err) {if (this._closed) {return cb(new Error('Pool is closed.'));}if (err) {return cb(err);}this.emit('connection', connection);return cb(null, connection);}.bind(this));}//檢查是否允許排隊(duì)等待(默認(rèn)True),False時(shí)直接拋錯(cuò)if (!this.config.waitForConnections) {return process.nextTick(function () {return cb(new Error('No connections available.'));});}//檢查排隊(duì)人數(shù)是否超過上限(默認(rèn)0,無(wú)限)if (this.config.queueLimit && this._connectionQueue.length >= this.config.queueLimit) {return cb(new Error('Queue limit reached.'));}//開始排隊(duì)this._connectionQueue.push(cb); };/*** 釋放Connection* @param connection*/ Pool.prototype.releaseConnection = function (connection) {var cb;//非連接池模式處理if (!connection._pool) {//如果有人排隊(duì)if (this._connectionQueue.length) {//出棧一個(gè)排隊(duì)回調(diào)cb = this._connectionQueue.shift();//調(diào)用getConnection返回Connection給予回調(diào)使用process.nextTick(this.getConnection.bind(this, cb));}}/***連接池模式處理 有人排隊(duì)*/else if (this._connectionQueue.length) {cb = this._connectionQueue.shift();//將釋放的connection直接給予排隊(duì)列表的第一個(gè)人使用process.nextTick(cb.bind(null, null, connection));}//連接池模式處理 無(wú)人排隊(duì)else {//將釋放的connection加入可用連接數(shù)組,待使用this._freeConnections.push(connection);//我本地加的日志console.log("releaseConnection _allConnections.length: %j, _freeConnections.length: %j", this._allConnections.length, this._freeConnections.length);} };轉(zhuǎn)載于:https://www.cnblogs.com/fengxiang/p/3555601.html
總結(jié)
以上是生活随笔為你收集整理的node-mysql中的连接池代码学习的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SCL语言(入门初级笔记)「建议收藏」
- 下一篇: iPhone如何清理内部储存空间?