首頁  >  文章  >  後端開發  >  MongoDB 事務,回呼 API 方式

MongoDB 事務,回呼 API 方式

WBOY
WBOY轉載
2024-02-06 09:35:03683瀏覽

MongoDB 事务,回调 API 方式

問題內容

在閱讀了許多有關 MongoDB 交易的文件/文章後,我仍然需要進一步澄清。

這裡說:

MongoDB provides two APIs to use transactions. The first is the core API which has similar syntax to relational databases. The second, the callback API, is the recommended approach to using transactions in MongoDB.

但它繼續介紹了核心 API 方法,而根本沒有觸及建議的方法。

這裡的官方文檔說,

This example highlights the key components of the transactions API. In particular, it uses the callback API. The callback API:

starts a transaction
executes the specified operations
commits the result (or aborts on error)

但是,當涉及最重要的「執行指定操作」步驟時,該範例沒有顯示任何相關程式碼。即,正如 MongoDB Transactions In NodeJS 中所問的,我「仍然需要一個真實的範例」。

PS。如果範例發生變更或消失,這裡是 Golang 版本:
// WithTransactionExample is an example of using the Session.WithTransaction function.
func WithTransactionExample(ctx context.Context) error {
    // For a replica set, include the replica set name and a seedlist of the members in the URI string; e.g.
    // uri := "mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017/?replicaSet=myRepl"
    // For a sharded cluster, connect to the mongos instances; e.g.
    // uri := "mongodb://mongos0.example.com:27017,mongos1.example.com:27017/"
    uri := mtest.ClusterURI()
    clientOpts := options.Client().ApplyURI(uri)
    client, err := mongo.Connect(ctx, clientOpts)
    if err != nil {
        return err
    }
    defer func() { _ = client.Disconnect(ctx) }()
    // Prereq: Create collections.
    wcMajority := writeconcern.Majority()
    wcMajority.WTimeout = 1 * time.Second
    wcMajorityCollectionOpts := options.Collection().SetWriteConcern(wcMajority)
    fooColl := client.Database("mydb1").Collection("foo", wcMajorityCollectionOpts)
    barColl := client.Database("mydb1").Collection("bar", wcMajorityCollectionOpts)
    // Step 1: Define the callback that specifies the sequence of operations to perform inside the transaction.
    callback := func(sessCtx mongo.SessionContext) (interface{}, error) {
        // Important: You must pass sessCtx as the Context parameter to the operations for them to be executed in the
        // transaction.
        if _, err := fooColl.InsertOne(sessCtx, bson.D{{"abc", 1}}); err != nil {
            return nil, err
        }
        if _, err := barColl.InsertOne(sessCtx, bson.D{{"xyz", 999}}); err != nil {
            return nil, err
        }
        return nil, nil
    }
    // Step 2: Start a session and run the callback using WithTransaction.
    session, err := client.StartSession()
    if err != nil {
        return err
    }
    defer session.EndSession(ctx)
    result, err := session.WithTransaction(ctx, callback)
    if err != nil {
        return err
    }
    log.Printf("result: %v\n", result)
    return nil
}

從範例中我看來,最重要的「執行指定操作」步驟是在回調中完成的。是這樣嗎?如果是這樣,官方文件確實需要強調這一點。


正確答案


範例已完成。它包含以下關鍵評論:

// Step 2: Start a session and run the callback using WithTransaction.

所以callback函數是由Session執行的.WithTransaction()# 方法。你將 callback 函數傳遞給它,它將被 Session.WithTransaction() 方法呼叫。

此實作確保回呼函數中完成的操作將作為交易執行(即,要么應用所有操作,要么不應用任何操作)。如果回呼函數傳回非nil錯誤,則交易將被中止,否則交易將被提交。

以上是MongoDB 事務,回呼 API 方式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除