做了一个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);