• 【Mongodb】事务


    概述

    • Mongodb 4.0 支持副本集的多文档事务
    • Mongodb 4.2 支持分片集群的多文档事务

    单个Server是不支持使用事务,所以要学习事务,需要搭建一个副本集/分片集群

    另外需要说明是,单个文档操作是原子操作,而mongodb是文档型数据库,在单个文档上,可以嵌入对象/数组这种格式来维护数据的关系,而不应该使用多个集合来维护数据之间的关系。由于mongodb的这种特性,所以单个文档操作消除了很多需要事务的需求。

    搭建副本集

    下面以最简单的方式搭建一个副本集

    1.  启动多个mongod实例,这里使用cmd命令启动

    start "Mongodb Service - 27017" /min mongod --port 27017 --replSet "rs0" --dbpath "F:DatabaseMongodbData27017" --logpath "F:DatabaseMongodbLogmongod.27017.log"
    start "Mongodb Service - 27018" /min mongod --port 27018 --replSet "rs0" --dbpath "F:DatabaseMongodbData27018" --logpath "F:DatabaseMongodbLogmongod.27018.log"

    参数说明

    • replSet : 设置副本集名称
    • port : 设置端口,因为我是单机,所以只能设置不同端口
    • dbpath: 数据文件路径,注:文件夹必须是存在,mongod不会自动创建
    • logpath: 日志文件名称,这个不需要提前新建,若不存在mongod会自动创建

    2.  连接任意一个实例,这里就选择27017这个默认端口

    mongo

    3. 启动副本集

    rs.initiate({
        _id: "rs0",
        members: [
            { _id: 0, host: "127.0.0.1:27017" },
            { _id: 1, host: "127.0.0.1:27018" }
        ]
    })

    参数说明

    • _id : 副本集名称,就是启动实例时指定那个名称
    • members : 这个就是所有成员,_id每个成员的标识,整数型[0,255]

    返回字段"ok" : 1 代表创建成功

    rs.initiate({}),这里除了几个必须的,都是使用默认配置去启动,更多配置参数可以参考replica-configuration

    4. 查看当前配置信息

    rs.conf()

    5. 查看副本集信息

    rs.status()

     

    到这,副本集就搭建完成

    事务

    1. 连接副本集

    mongo mongodb://127.0.0.1:27017,127.0.0.1:27018/?replicaSet=rs0

    可以直接连接主副本的实例,也可以用这种url形式可以自动连接主副本(推荐使用后者)

    2. 准备2条数据

    db.balance.insert({ name: "Wilson", balance: 100 }, { writeConcern: { w: "majority", wtimeout: 2000 } });
    db.record.insert({ name: "Wilson", change: 100, balance: 100, }, { writeConcern: { w: "majority", wtimeout: 2000 } });

    测试正常提交

    模拟一个扣钱动作,其中扣款和流水在一个事务里

    session = db.getMongo().startSession({ readPreference: { mode: "primary" } });
    balanceCol = session.getDatabase("mongo").balance;
    recordCol = session.getDatabase("mongo").record;
    session.startTransaction({ readConcern: { level: "local" }, writeConcern: { w: "majority" } });
    
    try {
        balanceCol.updateOne({ "name": "Wilson" }, { $set: { "balance": 50 } });
        recordCol.insertOne({ "name": "Wilson", change: -50, balance: 50 });
    } catch (error) {
        session.abortTransaction();
    } 
    session.commitTransaction();
    session.endSession();

    查看余额情况

    db.balance.aggregate([
        { $lookup: { from: "record", localField: "name", foreignField: "name", as: "changs" } },
        { $project: { "_id": 0, "changs._id": 0, "changs.name": 0 } },
    ]);

    结果,可以看到余额扣了,多了一条流水

    { "name" : "Wilson", "balance" : 50, "changs" : [ { "change" : 100, "balance" : 100 }, { "change" : -50, "balance" : 50 } ] }

    测试失败回滚

    事务内多增加一个插入不存在的集合操作,让事务报错

    session.startTransaction({ readConcern: { level: "local" }, writeConcern: { w: "majority" } });
    try {
        balanceCol.updateOne({ "name": "Wilson" }, { $set: { "balance": -50 } });
        recordCol.insertOne({ "name": "Wilson", change: -50, balance: 0 });
        session.getDatabase("mongo").user.insert({ "time": new Date() });    //多增加操作一个不存在的表
    } catch (error) {
        session.abortTransaction();
        throw error;
    }
    session.commitTransaction();
    session.endSession();

    返回报错信息,显示事务被中断了

    2020-04-15T21:37:05.576+0800 E  QUERY    [js] uncaught exception: Error: command failed: {
            "errorLabels" : [
                    "TransientTransactionError"
            ],
            "operationTime" : Timestamp(1586957825, 1),
            "ok" : 0,
            "errmsg" : "Transaction 0 has been aborted.",
            "code" : 251,
            "codeName" : "NoSuchTransaction",
            "$clusterTime" : {
                    "clusterTime" : Timestamp(1586957825, 1),
                    "signature" : {
                            "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
                            "keyId" : NumberLong(0)
                    }
            }
    } :
    _getErrorWithCode@src/mongo/shell/utils.js:25:13
    doassert@src/mongo/shell/assert.js:18:14
    _assertCommandWorked@src/mongo/shell/assert.js:583:17
    assert.commandWorked@src/mongo/shell/assert.js:673:16
    commitTransaction@src/mongo/shell/session.js:971:17
    @(shell):1:1
    
    

    再查看当前余额情况

    db.balance.aggregate([
        { $lookup: { from: "record", localField: "name", foreignField: "name", as: "changs" } },
        { $project: { "_id": 0, "changs._id": 0, "changs.name": 0 } },
    ]);

    可以看到,余额和流水都没变化。

    { "name" : "Wilson", "balance" : 50, "changs" : [ { "change" : 100, "balance" : 100 }, { "change" : -50, "balance" : 50 } ] }

     参考文章


    Replication — MongoDB Manual

    Transactions — MongoDB Manual

  • 相关阅读:
    php分页问题
    php中memcached的使用
    Linux安装Git
    day06
    day07
    day03
    day05
    day04
    列表的操作
    初识数据类型
  • 原文地址:https://www.cnblogs.com/WilsonPan/p/12708710.html
Copyright © 2020-2023  润新知