真实的国产乱ⅩXXX66竹夫人,五月香六月婷婷激情综合,亚洲日本VA一区二区三区,亚洲精品一区二区三区麻豆

成都創(chuàng)新互聯(lián)網(wǎng)站制作重慶分公司

【MongoDB】事務(wù)

事務(wù) Transactions

[TOC]

公司專注于為企業(yè)提供成都網(wǎng)站設(shè)計、網(wǎng)站制作、微信公眾號開發(fā)、成都商城網(wǎng)站開發(fā),小程序開發(fā),軟件按需求定制開發(fā)等一站式互聯(lián)網(wǎng)企業(yè)服務(wù)。憑借多年豐富的經(jīng)驗,我們會仔細了解各客戶的需求而做出多方面的分析、設(shè)計、整合,為客戶設(shè)計出具風(fēng)格及創(chuàng)意性的商業(yè)解決方案,成都創(chuàng)新互聯(lián)更提供一系列網(wǎng)站制作和網(wǎng)站推廣的服務(wù)。

譯者前言:

數(shù)據(jù)模型定義對照:

MySQLMongoDB
文檔
集合
組復(fù)制 復(fù)制集

專有名詞翻譯約定:

中文原文
讀一致性 readConcern
寫一致性 writeConcern

簡介:

4.0版本中加入

New in version 4.0

在MongoDB中,針對單個文檔的操作是原子性的。由于MongoDB允許在單個文檔中嵌入用以表示相互之間關(guān)系的子文檔和數(shù)組來替代跨文檔和集合的連接操作,這種折中的方式在很多場景下間接實現(xiàn)了多文檔事務(wù)的特性。

In MongoDB, an operation on a single document is atomic. Because you can use embedded documents and arrays to capture relationships between data in a single document structure instead of normalizing across multiple documents and collections, this single-document atomicity obviates the need for multi-document transactions for many practical use cases.

但這種辦法在面對多文檔同時更新或者多文檔一致性讀的時候就顯得捉襟見肘,MongoDB新版本提供了面向復(fù)制集的多文檔事務(wù)特性。其能滿足在多個操作,文檔,集合,數(shù)據(jù)庫之間的事務(wù)性,事務(wù)的特性:一個事務(wù)中的若干個操作要么全部完成,要么全部回滾,操作的原子性A,數(shù)據(jù)更新的一致性C。事務(wù)提交時,所有數(shù)據(jù)更改都會被永久保存D。事務(wù)提交前其數(shù)據(jù)更改不會被外部獲取到I。

However, for situations that require atomicity for updates to multiple documents or consistency between reads to multiple documents, MongoDB provides the ability to perform multi-document transactions against replica sets. Multi-document transactions can be used across multiple operations, collections, databases, and documents. Multi-document transactions provide an “all-or-nothing” proposition. When a transaction commits, all data changes made in the transaction are saved. If any operation in the transaction fails, the transaction aborts and all data changes made in the transaction are discarded without ever becoming visible. Until a transaction commits, no write operations in the transaction are visible outside the transaction.

注意:

在多數(shù)場景下,多文檔事務(wù)相對于單文檔數(shù)據(jù)變更性能損耗會更嚴重。且不要因為支持多文檔事務(wù)就妄圖放松對數(shù)據(jù)結(jié)構(gòu)設(shè)計的要求。無論哪種數(shù)據(jù)庫,巧妙的表設(shè)計總是會比頭鐵強行使用不必要的低級數(shù)據(jù)關(guān)聯(lián)來的高效。

一般情況下,由于減少了對多文檔事務(wù)的需求,非范式化(即內(nèi)嵌子文檔和數(shù)組)的數(shù)據(jù)模型還是會發(fā)揮比較大的作用

In most cases, multi-document transaction incurs a greater performance cost over single document writes, and the availability of multi-document transaction should not be a replacement for effective schema design. For many scenarios, the denormalized data model (embedded documents and arrays) will continue to be optimal for your data and use cases. That is, for many scenarios, modeling your data appropriately will minimize the need for multi-document transactions.

事務(wù)和復(fù)制集 Transactions and Replica Sets

多文檔事務(wù)在4.0版本僅支持復(fù)制集,對分片集群的事務(wù)性支持計劃在4.2版本中實現(xiàn)。

Multi-document transactions are available for replica sets only. Transactions for sharded clusters are scheduled for MongoDB 4.2 [1].

免責(zé)聲明,不翻譯了The development, release, and timing of any features or functionality described for our products remains at our sole discretion. This information is merely intended to outline our general product direction and it should not be relied on in making a purchasing decision nor is this a commitment, promise or legal obligation to deliver any material, code, or functionality.

新特性版本向后兼容度 Feature Compatibility Version (FCV)

想使用多文檔事務(wù)的特性的話, featureCompatibilityVersion值必須設(shè)為4.0以上。(開啟后,既存的數(shù)據(jù)不支持用4.0以下版本的mongod啟動)

The featureCompatibilityVersion (fCV) of all members of the replica set must be 4.0 or greater. To check the fCV for a member, connect to the member and run the following command:

db.adminCommand( { getParameter: 1, featureCompatibilityVersion: 1 } )

For more information on fCV, see setFeatureCompatibilityVersion.

存儲引擎 Storage Engines

多文檔事務(wù)特性僅支持WiredTiger存儲引擎

Multi-document transactions are only available for deployments that use WiredTiger storage engine.

Multi-document transactions are not available for deployments that use in-memory storage engine or the deprecated MMAPv1 storage engine.

事務(wù)與文檔操作 Transactions and Operations

注意事項:

For transactions:

? 可以在任何跨庫的表上進行CURD操作

  • You can specify read/write (CRUD) operations on existingcollections. The collections can be in different databases.

    config,admin,local庫中的表不支持多文檔事務(wù)

  • You cannot read/write to collections in the config, admin, or local databases.

    各庫中的system.*表不支持多文檔事務(wù)

  • You cannot write to system.* collections.

    在當(dāng)前會話的事務(wù)中無法進行返回當(dāng)前操作的查詢計劃

  • You cannot return the supported operation’s query plan (i.e. explain).

    在事務(wù)外創(chuàng)建的游標無法在事務(wù)中進行getMore操作

  • For cursors created outside of transactions, you cannot call getMore inside a transaction.

    在事務(wù)中創(chuàng)建的游標無法在事務(wù)外進行getMore操作

  • For cursors created in a transaction, you cannot call getMore outside the transaction.

在多文檔事務(wù)中無法進行諸如創(chuàng)建或者刪除集合,添加索引等更新數(shù)據(jù)庫元數(shù)據(jù)的操作。進一步的說,在多文檔事務(wù)中那些可能會隱式創(chuàng)建集合的操作也是被禁止的。

Operations that affect the database catalog, such as creating or dropping a collection or an index, are not allowed in multi-document transactions. For example, a multi-document transaction cannot include an insert operation that would result in the creation of a new collection. See Restricted Operations.

提示:

如果在創(chuàng)建或者刪除集合后會緊接著開啟一個會對該集合進行操作的事務(wù),那么創(chuàng)建或者刪除集合的操作需要追加寫一致性(writeConcern)擴散到多數(shù)節(jié)點的參數(shù)以確保事務(wù)可以成功獲取該集合相關(guān)的鎖。

(注,這段話可能較為拗口。其實是從集群的一致性來考慮,和事務(wù)的讀一致性readConcern相關(guān))

When creating or dropping a collection immediately before starting a transaction, if the collection is accessed within the transaction, issue the create or drop operation with write concern "majority" to ensure that the transaction can acquire the required locks.

目前支持多文檔事務(wù)的命令和方法

For multi-document transactions:

MethodCommandNote
db.collection.aggregate() aggregate Excluding the following stages:$collStats$currentOp$indexStats$listLocalSessions$listSessions$out
db.collection.distinct() distinct
db.collection.find() find
geoSearch
db.collection.deleteMany()db.collection.deleteOne()db.collection.remove() delete
db.collection.findOneAndDelete()db.collection.findOneAndReplace()db.collection.findOneAndUpdate() findAndModify For upsert, only when run against an existing collection.
db.collection.insertMany()db.collection.insertOne()db.collection.insert() insert Only when run against an existing collection.
db.collection.save() If an insert, only when run against an existing collection.
db.collection.updateOne()db.collection.updateMany()db.collection.replaceOne()db.collection.update() update For upsert, only when run against an existing collection.
db.collection.bulkWrite()Various Bulk Operation Methods For insert operations, only when run against an existing collection.

計數(shù)操作 Count Operation

如果需要在事務(wù)中進行計數(shù)操作,需要使用 $count 操作符或者把 $group$sum結(jié)合起來

To perform a count operation within a transaction, use the $count aggregation stage or the $group (with a$sum expression) aggregation stage.

兼容4.0版本的MongoDB驅(qū)動內(nèi)含一個集合層級由 $group$sum 包裝出來的 countDocuments(filter,options) 計數(shù)接口

MongoDB drivers compatible with the 4.0 features provide a collection-level API countDocuments(filter,options) as a helper method that uses the $group with a $sum expression to perform a count.

獲取參數(shù)與信息相關(guān)的操作 Informational Operations

諸如 isMaster, buildInfo, connectionStatus (及其相關(guān)的幫助命令)這些獲取參數(shù)或者信息的命令可以在事務(wù)中使用,但不能作為事務(wù)中起手的第一個操作。

Informational commands, such as isMaster, buildInfo, connectionStatus (and their helper methods) are allowed in transactions; however, they cannot be the first operation in the transaction.

受到限制的操作 Restricted Operations

下列操作不允許在多文檔事務(wù)中使用:

The following operations are not allowed in multi-document transactions:

? 可能會影響到數(shù)據(jù)庫元信息的操作,諸如創(chuàng)建或者刪除集合,增加索引。(注:其實就是DDL操作吧)。

  • Operations that affect the database catalog, such as creating or dropping a collection or an index. For example, a multi-document transaction cannot include an insert operation that would result in the creation of a new collection.

    listCollectionslistIndexes 及其相關(guān)的幫助命令都在上述禁止之列。(注:這個有點意外)

    The listCollections and listIndexes commands and their helper methods are also excluded.

    非增刪改查和非查詢參數(shù)與信息的操作,諸如 createUser, getParameter, count及其幫助命令等等。

  • Non-CRUD and non-informational operations, such as createUser, getParameter, count, etc. and their helpers.

事務(wù)與數(shù)據(jù)庫安全相關(guān) Transactions and Security

? 如果啟用了鑒權(quán),欲使用多文檔事務(wù),必須擁有操作事務(wù)的權(quán)限。

  • If running with access control, you must have privileges for the operations in the transaction. [2]

    如果開啟了審計,回滾的事務(wù)仍然會被記錄。

  • If running with auditing, operations in an aborted transaction are still audited.
若使用了附加驗證方式,用戶名大小不能超過10KIf using $external authentication users (i.e. Kerberos, LDAP, x.509 users), the usernames cannot be greater than 10k bytes.

事務(wù)與會話相關(guān) Transactions and Sessions

事務(wù)是和會話緊密相關(guān)的,一個會話在其生命周期內(nèi)最多只能并發(fā)一個處于激活狀態(tài)的事務(wù)。

Transations are associated with a session. That is, you start a transaction for a session. At any given time, you can have at most one open transaction for a session.

重點 IMPORTANT

當(dāng)使用驅(qū)動進行連接時(非mongo shell連接),必須將會話與每個事務(wù)對應(yīng)起來。(注:多事務(wù)就要開啟多個連接會話類)。若在事務(wù)正在進行時會話退出,則事務(wù)會進行回滾

When using the drivers, you mustpass the session to each operation in the transaction.

If a session ends and it has an open transaction, the transaction aborts.

事務(wù)與驅(qū)動的兼容 Transactions and MongoDB Drivers

以下是支持多文檔事務(wù)的各語言最低驅(qū)動版本號:

Clients require MongoDB drivers updated for MongoDB 4.0.

JavaPythonC#NodeRubyPerlPHPCScala
3.8.0 3.7.0C 1.11.0 2.7 3.1.0 2.6.0 2.0.0 1.5.0 2.4.0

重點:IMPORTANT

如果想在事務(wù)中進行讀寫結(jié)合的操作,同樣必須把每個操作和會話對應(yīng)起來

To associate read and write operations with a transaction, you mustpass the session to each operation in the transaction. For examples, see Transactions and Retryable Writes.

事務(wù)與mongo shell工具 Transactions and the mongo Shell

下面這些mongo shell方法可以用于操作事務(wù):

The following mongo shell methods are available for transactions:

  • Session.startTransaction()
  • Session.commitTransaction()
  • Session.abortTransaction()

事務(wù)和重寫 Transactions and Retryable Writes

面向高可用應(yīng)用 HIGHLY AVAILABLE APPLICATIONS

無論是MongoDB還是關(guān)系型數(shù)據(jù)庫,與其連接的應(yīng)用都應(yīng)該設(shè)法處理事務(wù)提交過程的錯誤,設(shè)計事務(wù)的重新提做邏輯。

Regardless of the database system, whether MongoDB or relational databases, applications should take measures to handle errors during transaction commits and incorporate retry logic for transactions.

事務(wù)重做 Retry Transaction

無論 retryWrites 有沒有被設(shè)置為true,事務(wù)中獨立的寫操作總是是無法被重做的

The individual write operations inside the transaction are not retryable, regardless of whether retryWrites is set to true.

如果操作執(zhí)行時發(fā)生了錯誤,會返回一個包含名為 errorLabels 的數(shù)組字段。如果該錯誤是暫時性的, errorLabels 會包含一個 "TransientTransactionError"元素,標志著整個事務(wù)可以被重做。

If an operation encounters an error, the returned error may have an errorLabels array field. If the error is a transient error, the errorLabels array field contains "TransientTransactionError" as an element and the transaction as a whole can be retried.

例如,下面的下面的JAVA函數(shù)就實現(xiàn)了執(zhí)行事務(wù)并重做那些包含"TransientTransactionError"的錯誤。

(注:官方文檔有其他幾種語言的例程,這里選擇使用人數(shù)最多的JAVA)

For example, the following helper runs a function and retries the function if a "TransientTransactionError" is encountered:

void runTransactionWithRetry(Runnable transactional) {
    while (true) {
        try {
            transactional.run();
            break;
        } catch (MongoException e) {
            System.out.println("Transaction aborted. Caught exception during transaction.");

            if (e.hasErrorLabel(MongoException.TRANSIENT_TRANSACTION_ERROR_LABEL)) {
                System.out.println("TransientTransactionError, aborting transaction and retrying ...");
                continue;
            } else {
                throw e;
            }
        }
    }
}

提交操作可以被重做 Retry Commit Operation

提交操作本身是可以被重做的。如果事務(wù)在提交過程中遇到錯誤,驅(qū)動會自動忽略 retryWrites的設(shè)置進行一次重試。

The commit operations are retryable write operations. If the commit operation operation encounters an error, MongoDB drivers retry the operation a single time regardless of whether retryWrites is set to true.

如果事務(wù)提交的過程中發(fā)生錯誤,MongoDB會返回一個包含 errorLabels 的數(shù)組字段。如果錯誤是暫時性的, errorLabels 字段會包含一個"UnknownTransactionCommitResult"元素,標識這個事務(wù)可以被重新提交

If the commit operation encounters an error, MongoDB returns an error with an errorLabels array field. If the error is a transient commit error, the errorLabels array field contains"UnknownTransactionCommitResult" as an element and the commit operation can be retried.

盡管MongoDB驅(qū)動提供了一次事務(wù)重新提交機制,應(yīng)用方面仍應(yīng)該設(shè)計一個方法去處理事務(wù)提交過程中爆出的錯誤。

In addition to the single retry behavior provided by the MongoDB drivers, applications should take measures to handle "UnknownTransactionCommitResult" errors during transaction commits.

仍以JAVA為例:

void commitWithRetry(ClientSession clientSession) {
    while (true) {
        try {
            clientSession.commitTransaction();
            System.out.println("Transaction committed");
            break;
        } catch (MongoException e) {
            // can retry commit
            if (e.hasErrorLabel(MongoException.UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL)) {
                System.out.println("UnknownTransactionCommitResult, retrying commit operation ...");
                continue;
            } else {
                System.out.println("Exception during commit ...");
                throw e;
            }
        }
    }
}

事務(wù)與提交操作的重做 Retry Transaction and Commit Operation

將上文兩個邏輯結(jié)合起來,看下面的例程:(JAVA)

void runTransactionWithRetry(Runnable transactional) {
    while (true) {
        try {
            transactional.run();
            break;
        } catch (MongoException e) {
            System.out.println("Transaction aborted. Caught exception during transaction.");

            if (e.hasErrorLabel(MongoException.TRANSIENT_TRANSACTION_ERROR_LABEL)) {
                System.out.println("TransientTransactionError, aborting transaction and retrying ...");
                continue;
            } else {
                throw e;
            }
        }
    }
}

void commitWithRetry(ClientSession clientSession) {
    while (true) {
        try {
            clientSession.commitTransaction();
            System.out.println("Transaction committed");
            break;
        } catch (MongoException e) {
            // can retry commit
            if (e.hasErrorLabel(MongoException.UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL)) {
                System.out.println("UnknownTransactionCommitResult, retrying commit operation ...");
                continue;
            } else {
                System.out.println("Exception during commit ...");
                throw e;
            }
        }
    }
}

void updateEmployeeInfo() {
    MongoCollection employeesCollection = client.getDatabase("hr").getCollection("employees");
    MongoCollection eventsCollection = client.getDatabase("hr").getCollection("events");

    try (ClientSession clientSession = client.startSession()) {
        clientSession.startTransaction();

        employeesCollection.updateOne(clientSession,
                Filters.eq("employee", 3),
                Updates.set("status", "Inactive"));
        eventsCollection.insertOne(clientSession,
                new Document("employee", 3).append("status", new Document("new", "Inactive").append("old", "Active")));

        commitWithRetry(clientSession);
    }
}

void updateEmployeeInfoWithRetry() {
    runTransactionWithRetry(this::updateEmployeeInfo);
}

原子性 Atomicity

多文檔事務(wù)滿足ACID的原子性

Multi-document transactions are atomic:

? 當(dāng)一個事務(wù)被提交時,該事務(wù)內(nèi)部中所有的變更都會保存并且可以被其他會話的事務(wù)讀到。

  • When a transaction commits, all data changes made in the transaction are saved and visible outside the transaction. Until a transaction commits, the data changes made in the transaction are not visible outside the transaction.

    當(dāng)事務(wù)回滾時,事務(wù)內(nèi)部所有的變更都會被干凈的丟棄。比如,事務(wù)中的任一操作失敗后,事務(wù)回滾,當(dāng)前事務(wù)中所有的變更都會被丟棄,且不為其他會話所知。

  • When a transaction aborts, all data changes made in the transaction are discarded without ever becoming visible. For example, if any operation in the transaction fails, the transaction aborts and all data changes made in the transaction are discarded without ever becoming visible.

讀傾向性 Read Preference

多文檔事務(wù)中的讀操作必須使用primary傾向性,即從復(fù)制集的主實例

Multi-document transactions that contain read operations must use read preference primary.

All operations in a given transaction must route to the same member.

事務(wù)參數(shù)選項 Transaction Options (Read Concern/Write Concern)

session.startTransaction( {
   readConcern: { level:  },
   writeConcern: { w: , j: , wtimeout:  }
} );

讀一致性 Read Concern

多文檔事務(wù)支持三種讀一致性等級: "snapshot", "local", and "majority",即快照,本機,多數(shù)派

Multi-document transactions support read concern "snapshot", "local", and "majority":

? 針對本機和多數(shù)派的讀一致性等級,MongoDB在有些時候回使用更強的等級進行替換。(注:為啥?)

  • For "local" and "majority" read concern, MongoDB may sometimes substitute a stronger read concern.

    針對多數(shù)派讀一致性等級,如果事務(wù)使用此級別進行提交,事務(wù)操作都會讀到副本集中多數(shù)派已經(jīng)提交的數(shù)據(jù)。

  • For "majority" read concern, if the transaction commits with write concern “majority”, transaction operations are guaranteed to have read majority-committed data. Otherwise, the "majority" read concern provides no guarantees that read operations read majority-committed data.

    針對快照級別的讀一致性,如果。。。。?!竟俜轿臋n這兒是不是寫錯了】,如果事務(wù)使用快照級別的讀一致性進行提交,那么可以保證事務(wù)中的操作讀到的都是事務(wù)開始時的多數(shù)派事務(wù)快照。

  • For "snapshot" read concern, if the transaction commits with write concern “majority”, the transaction operations are guaranteed to have read from a snapshot of majority committed data. Otherwise, the "snapshot" read concern provides no guarantee that read operations used a snapshot of majority-committed data.

如果針對當(dāng)前事務(wù)設(shè)置讀一致性,而不是對事務(wù)中的獨立操作設(shè)置一致性,那該一致性會覆蓋事務(wù)中所有的事務(wù)。而且在事務(wù)中,事務(wù)粒度的一致性會覆蓋集合級別,數(shù)據(jù)庫級別,客戶端級別的讀一致性。

You set the read concern at the transaction level, not at the individual operation level. The operations in the transaction will use the transaction-level read concern. Any read concern set at the collection and database level is ignored inside the transaction. If the transaction-level read concern is explicitly specified, the client level read concern is also ignored inside the transaction.

可以在事務(wù)開始時對讀一致性進行設(shè)置。

You can set the transaction read concern at the transaction start.

如果缺省了事務(wù)級別的讀一致性設(shè)置,事務(wù)會繼承會話級別的讀一致性,如果會話級別也沒有設(shè)置讀一致性,那么會繼續(xù)向上繼承客y戶端層級設(shè)置的讀一致性。

If unspecified at the transaction start, transactions use the session-level read concern or, if that is unset, the client-level read concern.

寫一致性 Write Concern

如果針對當(dāng)前事務(wù)設(shè)置寫一致性,而不是對事務(wù)中的獨立操作設(shè)置一致性。那么在提交時,事務(wù)會使用自身的一致性去提交寫操作。事務(wù)中各個獨立操作忽略寫一致性,請不要徒勞設(shè)置。(注:這段原文語義模糊,這里認為本段原文與上段原文寫法不同,是為了和上段中的情況進行區(qū)分)

You set the write concern at the transaction level, not at the individual operation level. At the time of the commit, transactions use the transaction level write concern to commit the write operations. Individual operations inside the transaction ignore write concerns. Do not explicitly set the write concern for the individual write operations inside transactions.

可以在事務(wù)開始時對讀一致性進行設(shè)置。

You can set the write concern for the transaction commit at the transaction start.

? 如果缺省了事務(wù)級別的寫一致性設(shè)置,那么事務(wù)在提交時會繼承會話級別的寫一致性,會話級別也缺省了設(shè)置的話,會繼續(xù)向上繼承客戶端級別的寫一致性。

  • If unspecified at the transaction start, transactions use the session-level write concern for the commit or, if that is unset, the client-level write concern.

    不支持寫一致性設(shè)置為w: 0

  • Write concern w: 0 is not supported for transactions.

    如果使用 w: 1 進行提交,那么該事務(wù)提交時只會確認本機oK,也就是PrimaryOK。如果主節(jié)點掛掉,且該事務(wù)沒有被傳輸?shù)疆?dāng)時的次級節(jié)點。那么,恭喜你,該事務(wù)大概率會被回滾掉。會造成數(shù)據(jù)庫端和應(yīng)用端數(shù)據(jù)的不一致和數(shù)據(jù)缺失。

  • If you commit using w: 1 write concern, your transaction can be rolled back if there is a failover.

    如果事務(wù)使用多數(shù)派寫一致性進行提交,且指定了快照級別的讀一致性。那么事務(wù)操作會確保從事務(wù)開始時多數(shù)派已經(jīng)提交的快照數(shù)據(jù)中進行讀取。(注:這段語義不明,官方文檔到底在表達什么,是不是寫錯了)

  • If the transaction commits with write concern “majority” and has specified read concern "snapshot" read concern, transaction operations are guaranteed to have read from a snapshot of majority-committed data. Otherwise, the "snapshot" read concern provides no guarantees that read operations used a snapshot of majority-committed data.

    如果事務(wù)使用多數(shù)派寫一致性進行提交,且指定了多數(shù)派級別的讀一致性,那么事務(wù)中的操作會被確保從多數(shù)派已提交的數(shù)據(jù)中進行讀取。(注:這個是不是官方文檔編輯時復(fù)制粘貼錯了,把上面讀一致性的內(nèi)容放過來了)

  • If the transaction commits with write concern “majority” and has specified read concern "majority" read concern, transaction operations are guaranteed to have read majority-committed data. Otherwise, the"majority" read concern provides no guarantees that read operations read majority-committed data.

事務(wù)和鎖 Transactions and Locks

事務(wù)中的操作在獲取其所需要數(shù)據(jù)上的鎖時,默認等待超時時間為5毫秒,超時后,當(dāng)前事務(wù)會被回滾。(注:這個太短了吧,幸好可以手動設(shè)置)

By default, transactions waits 5 milliseconds to acquire locks required by the operations in the transaction. If the transaction cannot acquire its required locks within the 5 milliseconds, the transaction aborts.

提示:

如果在創(chuàng)建或者刪除集合后會緊接著開啟一個會對該集合進行操作的事務(wù),那么創(chuàng)建或者刪除集合的操作需要追加寫一致性(writeConcern)擴散到多數(shù)節(jié)點的參數(shù)以確保事務(wù)可以成功獲取該集合相關(guān)的鎖。

(注,這段話可能較為拗口。其實是從集群的一致性來考慮,和事務(wù)的讀一致性readConcern相關(guān))

When creating or dropping a collection immediately before starting a transaction, if the collection is accessed within the transaction, issue the create or drop operation with write concern "majority" to ensure that the transaction can acquire the required locks.

可以使用 maxTransactionLockRequestTimeoutMillis 參數(shù)對鎖等待超時長度進行設(shè)置。

You can use the maxTransactionLockRequestTimeoutMillis parameter to adjust how long transactions wait to acquire locks.

也可以將 maxTransactionLockRequestTimeoutMillis 設(shè)為-1,以禁用鎖等待超時回滾,該事務(wù)會一直等待自己所需要的鎖被其他事務(wù)或者會話釋放。

You can also use operation-specific timeout by setting maxTransactionLockRequestTimeoutMillis to -1.

Transactions release all locks upon abort or commit.

原文鏈接:MongoDB document:Transactions

翻譯:張銳志


名稱欄目:【MongoDB】事務(wù)
鏈接分享:http://weahome.cn/article/peisji.html

其他資訊

在線咨詢

微信咨詢

電話咨詢

028-86922220(工作日)

18980820575(7×24)

提交需求

返回頂部