orm-transaction 的并发问题
单个请求的时候是 打印日志是
BEGIN
SELECT
UPDATE
COMMIT
但是并发多了以后就不是配对执行开始乱了
比如100个请求,最后更新的status应该是100 但是最后查询 status远小于100
测试代码
app.js
var express = require('express');
var orm = require('orm');
var app = express();
var UserService=require('./userservice');
app.listen(80);
app.get("/", function (req, res) {
UserService.readAndWrite(function(err,data){
res.send("<h1>"+data+"</h1>");
});
});
userservice.js
var mydb=require('./orm-db');
exports.readAndWrite =function(cb) {
mydb.transCommit(function(err,db){
var User = db.define("person", {
id : { type: 'serial', key: true },
name : String,
status :Number
});
db.transaction(function(err, txn){
User.find({id:2}, function (err, row) {
// console.log("Task found: ", row.length);
if(err){ return console.log(err) };
if(row[0]) {
row[0].status +=1;
row[0].save(function(err){
if(err){ return cb(err,'error'); };
// console.log("saved");
txn.commit(function(err){
if(err){ return console.log(err) };
// console.log("committed");
return cb(err,row[0].status);
});
/**/
});
}
/*
txn.commit(function (err) {
if (!err) {
console.log("success!");
}
});
*/
});
});
});
}
orm-db.js
//https://github.com/dresende/node-orm-transaction
var orm=require('orm');
var transaction = require("orm-transaction");
var opts = {
database: "test",
protocol: "mysql",
host: "127.0.0.1",
Personname: "test",
password: "test",
query: {
pool: true,
debug:true
},
};
var connection = null;
exports.transCommit=function(cb) {
if (connection){
return cb(null, connection);
}
orm.connect(opts,function(err,db){
db.use(transaction);
// console.log(db.transaction);
connection = db;
db.settings.set('instance.cache', false);
cb(err,db);
});
}