gpt4 book ai didi

javascript - NodeJS/express : server hanged after start running for a while

转载 作者:太空宇宙 更新时间:2023-11-03 22:26:14 27 4
gpt4 key购买 nike

我使用express和webpack来提供服务,一开始效果很好。奇怪的是,一段时间后服务(服务器)就会挂起。正如屏幕截图所示,没有收到消息代码。 (server message screenshot)而且这种情况一再发生。

我的app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var users = require('./routes/users');

var app = express();
var mysql = require('mysql');

var generals = require('./routes/generals');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use('/generals', generals);
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});

// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};

// render the error page
res.status(err.status || 500);
res.render('error');
});

module.exports = app;

这是路由文件:generals.js

var express = require('express');
var bodyParser = require('body-parser');

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

router.get('/dropDownValue/', function(req, res, next) {
pool.getConnection(function(err, connection) {
connection.query("select * from drop_down_value order by id desc", function(err, rows) {
if (!err && rows.length > 0) {
res.json(rows);
} else {
res.json([]);
}
});
});
});
连接文件:

var mysql = require('mysql');

var pool = mysql.createPool({
host: 'xxx',
user: 'xxx',
password: 'xxx',
database: 'xxx'
});

exports.getConnection = function (callback) {
pool.getConnection(callback);
};

最佳答案

当您使用pool.getConnection()时,一旦完成连接(即查询完成),您需要再次将连接释放回池中:

pool.getConnection(function(err, connection) {
connection.query("select * from drop_down_value order by id desc", function(err, rows) {

connection.release(); // <- this

if (!err && rows.length > 0) {
res.json(rows);
} else {
res.json([]);
}
});
});

否则,一旦执行了 10 次查询,池中就没有更多可用连接,它将开始(无限期地)等待连接被释放,从而挂起请求。

关于javascript - NodeJS/express : server hanged after start running for a while,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45944460/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com