我实现了即时消息Web应用程序。我想在我的mongodb数据库中保存聊天消息。如果每秒200条消息被推送到我的服务器花了30%我的CPU核心。我认为我的node.js Web应用程序性能不佳。 你能帮助我为我的即时消息Web应用程序实现一个好的架构吗?我想从客户端到服务器每秒至少推送5000条消息,这些消息在我的CPU核心上花费不到50%。
由于
这是我的app.js
// Setup basic express server
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 3000;
var mongoose = require('mongoose');
var configDB = require('./config/database.js');
// Database Models ===============================================================
var Message = require('./models/message');
// configuration ===============================================================
mongoose.connect(configDB.url);
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
io.on('connection', function (socket) {
// when the client emits 'new message', this listens and executes
socket.on('new message', function (data) {
// we tell the client to execute 'new message'
var message = new Message({text: data});
message.save(function (err) {
if (err) return handleError(err);
console.log('saved ' + data);
});
socket.broadcast.emit('new message', {
username: socket.username,
message: data
});
});
// when the user disconnects.. perform this
socket.on('disconnect', function () {
});
});
配置/ database.js
module.exports = {
'url' : 'mongodb://localhost/chatdb'
};
message.js
var mongoose = require('mongoose');
var messageSchema = new mongoose.Schema({
room_id: { type: String, required: false },
member_id: { type: String, required: false },
text: { type: String, required: false },
});
var Message = mongoose.model('Message', messageSchema);
module.exports = Message;