LiuXuFei
V2EX  ›  Node.js

事务处理速度太快导致数据出错?

  •  
  •   LiuXuFei · Apr 23, 2016 · 4715 views
    This topic created in 3861 days ago, the information mentioned may be changed or developed.
    有两个 MySQL 数据库表 a 和 b
    a 有一个整型字段 a_count(此字段某些情况下归 0)
    b 有一个整型字段 b_count

    事务处理:
    1 、 select 表 a ,得到 a_count ,然后计算 count = a_count + 1
    2 、 update 表 a , a_count = count
    3 、 insert 一条记录到表 b , b_count = count

    想实现的的情况 count : 1 2 3 4 5 6 7 1 2 3 4 5 6 (第二个 1 是因为 a_count 归零了)
    得到的真实情况 count : 1 2 2 2 3 3 4 1 1 2 3 3 3 (操作的速度太快导致数据重复)

    问题一:有什么方式可以解决这样的问题?
    问题二:解决了第一个问题,如果我想限制一个时间内(如:一秒)只能一次操作有哪些方式?

    上代码(语言 Node.js ,用得 orm 是 sequelize )

    models.sequelize.transaction(function (t) {

    // 查询表 a 数据
    return models.A.findOne({
    where: {
    id: user_id,
    },
    transaction: t,
    }).then(function (a) {

    var count = a.a_count + 1;

    // 事务:新增表 b 记录
    return models.B.create({
    b_count: count,
    }, {transaction: t}).then(function () {

    // 事务:更新表 a 数据
    return models.A.update({
    a_count: count,
    }, {
    where: {
    id: user_id,
    },
    transaction: t,
    }).then(function () {
    res.json({success: 'success'});
    });
    });
    });
    });
    6 replies  •  2016-04-23 12:29:50 +08:00
    agui2200
    agui2200
    Apr 23, 2016❤️1
    1
    加锁
    LiuXuFei
    LiuXuFei
    OP
    Apr 23, 2016
    3
    第二个问题有什么好的解决方式吗?
    hcymk2
    hcymk2
    Apr 23, 2016
    4
    count = a_count + 1
    这个不能直接在 sql 里面做么?
    bqbkbz
    bqbkbz
    Apr 23, 2016
    5
    拿着锁 sleep 1000ms
    LiuXuFei
    LiuXuFei
    OP
    Apr 23, 2016
    6
    @hcymk2 多个地方用注意统一
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1007 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 18:44 · PVG 02:44 · LAX 10:44 · JFK 13:44
    ♥ Do have faith in what you're doing.