nodejs處理高並發問題


 

做了一個nodejs並發測試,先描述一下環境 數據庫mysql,大概兩張表,讀取第一張表test的數據,拿出來-1,存到第二張testlog表記錄一下,用jmeter同事模擬50個請求,結果發現,部分數據沒有-1成功

test 表數據 id num desc 1 94 2017-02-28 14:41:17:86 testlog 表數據 id, testid, num, desc 4 1 99 2017-02-28 14:32:42:28 5 1 98 2017-02-28 14:32:43:76 6 1 97 2017-02-28 14:32:44:89 7 1 97 2017-02-28 14:32:44:88 8 1 97 2017-02-28 14:32:44:28 9 1 97 2017-02-28 14:32:44:86 10 1 97 2017-02-28 14:32:44:45 11 1 97 2017-02-28 14:32:45:48 12 1 97 2017-02-28 14:32:45:49 推測可能是同時修改數據,某一個現在沒有修改完畢,下一個線程已經讀取過了,導致數據更新不一致,但是nodejs不都是單線程的嗎,請各位大神解析一下,謝謝 代碼如下
var http = require('http'); var url = require('url'); var util = require('util'); http.createServer(function (req, res) { res.writeHead(200, { "Content-Type": "text/html;charset=utf-8" }); res.end("OK"); var mysql = require('mysql'); var connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '123456', database: 'myData' }); connection.connect(); connection.query('SELECT * from test', function (err, rows, fields) { if (err) { console.log(err); return; }; var test = rows[0]; //讀取num var num = test.num - 1; var id = test.id; connection.query("update test set num=" + num + ",`desc`='" + dateFormat(new Date()) + "'", function (err, res) { if (!err) { var insert = "insert into testlog(testid,num,`desc`) values ('" + id + "','" + num + "','" + dateFormat(new Date()) + "')"; connection.query(insert, function (err, res) { if (!err) { connection.end(); console.log("update sucess!"); } else { console.log(err); } }); } else { connection.end(); console.log(err); } }); }); function dateFormat(date) { var fmt = "yyyy-MM-dd hh:mm:ss:SS"; var o = { "M+": date.getMonth() + 1, //?? "d+": date.getDate(), //? "h+": date.getHours(), //С? "m+": date.getMinutes(), //? "s+": date.getSeconds(), //? "q+": Math.floor((date.getMonth() + 3) / 3), //?? "S+": date.getMilliseconds() //?ī }; if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length)); } for (var k in o) { if (new RegExp("(" + k + ")").test(fmt)) { fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); } } return fmt; } }).listen(3000);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM