我有一个非常简单的RESTful服务器,它基本上通过mongoose客户端从数据库添加/获取数据。服务器是一个亚马逊微实例,我觉得奇怪的是,检查我的服务器统计数据,它有时显示50%的CPU使用率和极低的并发性的高峰 - 我说的是不超过10个用户的东西)。看看图片就可以了解这个想法。
请忽略时间,因为它是另一个时区。
我能想到的唯一问题是我没有编写正确的“node.js”回调代码。这是我的主要模型,其中的函数由routee调用。
var _ = require('underscore'),
mongoose = require('mongoose'),
sanitize = require('validator').sanitize,
Validator = require('validator').Validator,
redis = require('../models/reds'),
v = new Validator();
v.error = function(msg){
return false;
};
var itemSchema = mongoose.Schema({
adm: { type: String },
url: { type: String, required: true },
desc: { type: String, required: true, trim: true },
tags: { type: [String] },
}, { autoIndex: false }).index({ tags: 1 });
var Male = mongoose.model('Male', itemSchema),
Female = mongoose.model('Female', itemSchema);
var idFromTime = function(time){
var createId = function(int){ return mongoose.Types.ObjectId(int + '0000000000000000') };
if(!time)
return createId(Math.round(new Date().getTime() / 1000).toString(16));
else return createId(time);
};
exports.getPhotos = function(options, next){
var query,
parameters = {},
tags = [];
if( v.validate(options.tags).is(/^[-\sa-z]+$/) && options.tags != 'undefined' ){
tags = options.tags.split(' ');
parameters['tags'] = { '$all': tags };
}
if(options.time && options.time.length == 8 && options.time.match(/[0-9a-f]+/))
parameters['_id'] = { '$lt': idFromTime(options.time) };
else parameters['_id'] = { '$lt': idFromTime() };
if(options.female == true || options.male == false) query = Female.find(parameters);
else if(options.male == true || options.female == false) query = Male.find(parameters);
query
.limit(29)
.sort('-_id')
.select('url desc')
.exec(function(err, items) { next(err, items) });
};
exports.addPhoto = function(options, next){
var photo,
parameters,
tags = [];
if(
options.desc != 'undefined' &&
v.validate(options.desc).len(2, 100) &&
v.validate(options.url).isUrl() &&
v.validate(options.tags).is(/^[-\sa-z]+$/) ){
tags = options.tags.split(' ');
tags = _.compact(tags)
tags = _.uniq(tags);
parameters = {
adm: options.admin,
url: options.url,
desc: options.desc,
tags: tags,
};
} else {
next(true);
return false;
}
if(options.female == true || options.male == false) photo = new Female(parameters);
else if(options.male == true || options.female == false) photo = new Male(parameters);
photo.save(function(err, photo){
next(err, photo);
});
};
exports.getComments = function(id, next){
redis.lrange(id, 0, -1, function(err, list){
next(err, list);
});
};
exports.setComment = function(id, text, next){
if(!text || 0 === text.length) {
next(true);
} else{
redis.multi()
.lpush(id, text)
.ltrim(id, 0, 19)
.expire(id, 2628000)
.exec(function(err, reply){
if(!err)
next(false);
else next(true);
});
}
}
我有mongodb& redis也在服务器上运行,并且在我的网站中显示唯一的单页我同时使用了jade和amp;手写笔。
我的代码是否存在任何与性能相关的问题,或者我可以放心,它只是微观实例不像我想象的那样高效?