nodejs解决mysql和连接池(pool)自动断开问题

2017-07-14 13:53:02

  最近在做一个个人项目,数据库尝试使用了mongodb、sqlite和mysql。分享一下关于mysql的连接池用法。项目部署于appfog,项目中我使用连接池链接数据库,本地测试一切正常。上线以后,经过几次请求两个数据接口总是报503。一直不明就里,今天经过一番排查终于顺利解决了。
1.mysql 链接普通模式

[javascript] view plain copy

  1. var mysql = require('mysql'),  

  2.     env = {  

  3.       host : 'localhost',  

  4.       user : 'root',  

  5.       password : '2212',  

  6.       database : 'image_marker'  

  7.     };  

  8.   

  9.   db = mysql.createConnection(env);  

  10.   db.connect();  

  11.   

  12.   exports.do = function (sql, callback) {  

  13.   

  14.     db.query(sql, callback);  

  15.   

  16.   }  


MySQL中有一个名叫wait_timeout的变量,表示操作超时时间,当连接超过一定时间没有活动后,会自动关闭该连接,这个值默认为28800(即8小时)。对于这种普通连接的方式,在正式线上可能会遇到连接丢失的问题(No reconnection after connection lost错误日志),上github上看了下文档和issues,上面说到连接丢失后不会自动重新连接,会触发error事件。 所以可以使用下面这种方法来避免连接对视问题:


[javascript] view plain copy

  1. function handleError (err) {  

  2.   if (err) {  

  3.     // 如果是连接断开,自动重新连接  

  4.     if (err.code === 'PROTOCOL_CONNECTION_LOST') {  

  5.       connect();  

  6.     } else {  

  7.       console.error(err.stack || err);  

  8.     }  

  9.   }  

  10. }  

  11.   

  12. // 连接数据库  

  13. function connect () {  

  14.   db = mysql.createConnection(config);  

  15.   db.connect(handleError);  

  16.   db.on('error', handleError);  

  17. }  

  18.   

  19. var db;  

  20. connect();  


 
2.使用连接池
 
对于丢失连接的问题,可以使用连接池(最新版mysql模块,用mysql.createPool()来创建的pool,当触发了connection的error事件时,会把该connection对象从连接池中移除。)

[javascript] view plain copy

  1. var mysql = require('mysql');  

  2. var pool  = mysql.createPool(config);  

  3.   

  4. pool.getConnection(function(err, connection) {  

  5.   // Use the connection  

  6.   connection.query( 'SELECT something FROM sometable'function(err, rows) {  

  7.     // And done with the connection.  

  8.     connection.end();  

  9.   

  10.     // Don't use the connection here, it has been returned to the pool.  

  11.   });  

  12. });  


  • 2017-02-13 17:50:05

    cURL error 60: SSL certificate problem: unable to get local issuer certificate

    Drupal 8 version uses Guzzle Http Client internally, but under the hood it may use cURL or PHP internals. If you installed PHP cURL on your PHP server it typically uses cURL and you may see an exception with error Peer certificate cannot be authenticated with known CA certificates or error code CURLE_SSL_CACERT (60).

  • 2017-02-16 08:09:01

    HTML中PRE和p的区别

    pre 元素可定义预格式化的文本。被包围在 pre 元素中的文本通常会保留空格和换行符。而文本也会呈现为等宽字体。 <pre> 标签的一个常见应用就是用来表示计算机的源代码。

  • 2017-02-16 15:14:14

    动态加载js和css

    开发过程中经常需要动态加载js和css,今天特意总结了一下常用的方法。