首页 > 后端开发 > Golang > 正文

MongoDB 事务,回调 API 方式

WBOY
发布: 2024-02-06 09:35:03
转载
766人浏览过

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中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:stackoverflow网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门推荐
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号