nodejs接口阻塞、响应慢

nodejs采用异步回调的方式应该是可以满足高并发的,
但是在使用postman进行接口压力测试时发现,
上一个接口获得响应后,下一个接口才请求,并且响应的时间为一秒多

是因为nodejs连接数据库没有使用连接池?
还是因为没有使用redis?
还是因为我的测试方法有问题?

var express = require("express");

var fs = require('fs');

var path = require('path');

var crypto = require('crypto'); //加载加密文件

var router = express.Router();

var MongoClient = require('mongodb').MongoClient;

var ObjectID = require('mongodb').ObjectID;

var url = "mongodb://localhost:27017/books";

// 缓存区

var buf = new Buffer.alloc(2048);

// app端注册

router.post('/enroll', function(req, res){

var data = {

userName: req.body.userName,

sex: req.body.sex,

userPhone: req.body.userPhone,

userEmail: req.body.userEmail,

password: req.body.password,

status: 1

}

for(var k in data){

if(!data[k]){

res.json({code:4, content:"参数异常"});

return false

}

}

MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {

if (err) throw err;

var dbo = db.db("books");

dbo.collection("user").find({userPhone: data.userPhone}).count(function(err, num){

if(err) throw err;

if(num == 0){

// 密码加密

var pwObj = encrypt(data.password);

data.password = pwObj.pw;

data.key = pwObj.key;

dbo.collection("user").insertOne(data, function(err, result) {

if (err){

res.json({code:4, content: "服务器异常"});

throw err;

}

res.json({code:1, content: "添加成功"});

})

}else{

res.json({code:2, content: "此手机号码已注册"})

}

db.close();

});

});

});

// APP端验证登录

router.post('/login', function(req, res){

var userPhone = req.body.userPhone;

var password = req.body.password;

console.log(userPhone);

console.log(password);

if(userPhone && password){

MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {

if (err) throw err;

var dbo = db.db("books");

dbo.collection("user").find({userPhone: userPhone}).toArray(function(err, resArr) {

if (err) throw err;

if(resArr.length>0){

password = password + resArr[0].key;

var md5 = crypto.createHash('md5');

var r = md5.update(password).digest('hex');

if(r == resArr[0].password){

res.json({code: 1, content: resArr[0]._id});

}else{

res.json({code: 2, content: "密码错误"});

}

}else{

res.json({code: 2, content: "该手机号暂未注册"});

}

db.close();

});

});

}else{

res.json({code: 4, content: "参数异常"});

}

});

图片描述

回答:

是我的测试方法有问题,公司测试工程师帮忙测试的50条并发4秒完成,不过每一个请求耗时一秒多,去掉操作数据库的代码后,只需要200毫秒,说明操作数据库需要优化,应该是采用Redis做缓存

以上是 nodejs接口阻塞、响应慢 的全部内容, 来源链接: utcz.com/p/197348.html

回到顶部