我正在创建一个聊天应用程序,其中的node.js服务器计算所有消息的字符数。例如,有100个人发送消息,每个消息的长度为10,则意味着总字符数为1000(100 * 10)。如果此后再发送长度为10的消息,则字符总数应为1010(1000 + 10)。
所有消息均发送到node.js服务器,对其长度进行计数并保存在数据库中。
很多人同时发送消息时发生了一个大问题。
jMeter在我发送100条消息时,每条消息的长度为10(如上面的示例)在同一时间,总字符数为120。这应该是准确的1000!
这是我的代码(节点版本8.13.0):
'use strict'
const express = require('express');
const router = express.Router();
const co = require('co');
const models = require('models');
const Mutex = require('async-mutex').Mutex;
const CharacterCounter = models.CharacterCounter;
router.get('/message',function (req,res,next) {
co(function* () {
const originalText = req.body.message;
const mutex = new Mutex();
const release = yield mutex.acquire();
let addedCount = 0;
try {
const { currentCount } = yield CharacterCounter.findOne(); // get total character count so far
addedCount = currentCount + originalText.length;
yield CharacterCounter.updateTotalCharacterCount(addedCount); // save on DB
} catch (e) {
console.log(e);
} finally {
release();
}
// ... my code is keep going
似乎此问题的原因在互斥库中。但是我不知道确切的解决方案。有人有实现我目标的想法吗?我最近才刚刚开始使用node.js,因此不胜感激。