node如何应对sql查询导致的进程终止

zhangsheng_1992 2016-07-01 06:30:42
楼主最近在学习node开发web

基本环境如下
os centos6.5
webservice nginx port 80 前端代理
nodeservice port 9000
database mysql
frame express
view engine jade

今天在做一个列表查询的时候 发现如果sql查询语句错误 将会导致node进程挂掉 试着用了下keepalived监控了下node的端口 挂掉后重新启动 有如下问题:
1.如果监听的间隔设置的太长 应用可用性比较差 重启前将有一段空白期
2.如果设置间隔小 比如每秒都去监控的话 会导致keepalived的监听进程压力过高 容易导致监听进程挂掉
3.试着用了下try catch 结果不是很好

主要代码如下 router/index.js

var express = require('express');
var router = express.Router();
var model = require('../model/model');

router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});

router.get('/mysql',function(req,res,next){
//此处的参数为requset中请求的参数
model.query({type:'select',table: 'filmplan',where: ' versions = \'2D\'',order: 'id desc',limit: '10'},function(data,sql){
res.render('list/list', { data: data });
});
});
module.exports = router;


model.js

var mysql=require('mysql');
var connection = mysql.createConnection({
host : '127.0.01',
user : 'root',
password : '426759',
database : 'test',
port:'3306'
});

connection.connect();

var query = function (condition,callback){
var sql = createSql(condition);
if(sql === false){
callback(false);
}
connection.query(sql,function(err,rows,fields){
if (err) {
connection.rollback(function() {
throw err;
});
}
callback(rows,sql);
});
};

function createSql(condition){
if(typeof(condition.type) == 'undefined'){
return false;
}
var sql;
switch(condition.type){
case 'select':
sql = select(condition);
break;
case 'delete':
sql = del(condition);
break;
case 'update':
sql = update(condition);
break;
case 'insert':
sql = insert(condition);
break;

}
return sql;
}

function select(condition){
var sql = 'SELECT ';
if(typeof(condition.filed) == 'undefined'){
sql += '*';
}else{
sql += condition.filed;
}
if(typeof(condition.table) == 'undefined'){
return false;
}
sql += ' from '+condition.table;
if(typeof(condition.where) != 'undefined'){
sql += ' where '+condition.where;
}
if(typeof(condition.group) != 'undefined'){
sql += ' group by '+condition.order;
}
if(typeof(condition.order) != 'undefined'){
sql += ' order by '+condition.order;
}
if(typeof(condition.limit) != 'undefined'){
sql += ' limit '+condition.limit;
}
return sql;
}

exports.query = query;

list.js 模版解析一般不会出问题 但还是贴出来吧

html
title
body
table.table#mytable
tr
td
td
td
td
each item in data
tr
td= item.id
td= item.cenimaName
td= item.filmName
td= item.versions


想解决问题如下 如何保证在sql语句错误导致mysql报错时 或者说node在执行过程中遇到致命错误时 保证进程不挂掉 望大神赐教
@无聊码农
@娃都会打酱油了
...全文
221 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_24455705 2016-07-10
  • 打赏
  • 举报
回复
http://www.oschina.net/question/433035_171960 看这里
  • 打赏
  • 举报
回复
没用过node.js。。。。放try。。。catch语句里面试试?

87,997

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧