Maison  >  Article  >  développement back-end  >  Transaction MongoDB, méthode API de rappel

Transaction MongoDB, méthode API de rappel

WBOY
WBOYavant
2024-02-06 09:35:03679parcourir

MongoDB 事务,回调 API 方式

Contenu de la question

Après avoir lu de nombreux documents/articles sur les transactions MongoDB, j'ai encore besoin de précisions supplémentaires.

Ici, il est écrit :

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.

Mais il présente ensuite les méthodes de base de l'API sans toucher du tout aux méthodes recommandées.

La documentation officielle ici dit :

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)

Cependant, lorsqu'il s'agit de l'étape très importante « effectuer l'action spécifiée », l'exemple ne montre aucun code pertinent. Autrement dit, j'ai "encore besoin d'un exemple réel", comme demandé dans MongoDB Transactions In NodeJS.

PS. Au cas où les exemples changeraient ou disparaîtraient, voici la version 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
}

Il me semble, d'après l'exemple, que l'étape la plus importante "effectuer l'action spécifiée" est effectuée dans le rappel. est-ce ainsi? Si tel est le cas, la documentation officielle doit vraiment le souligner.


Bonne réponse


Exemple complété. Il contient les commentaires clés suivants :

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

Alorscallback函数是由Session执行的.WithTransaction() méthode. Vous appellerez la méthode callback 函数传递给它,它将被 Session.WithTransaction().

Cette implémentation garantit que les opérations terminées dans la fonction de rappel seront exécutées comme une transaction (c'est-à-dire que soit toutes les opérations sont appliquées, soit aucune opération n'est appliquée). Si la fonction de rappel renvoie une erreur non nil, la transaction sera abandonnée, sinon la transaction sera validée.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer