代码之家  ›  专栏  ›  技术社区  ›  Insub

使用mongo驱动程序的MongoDB事务

  •  0
  • Insub  · 技术社区  · 1 年前
    bool
    create_and_insert_doc (mongoc_client_session_t *session,
                           void *ctx,
                           bson_t **reply, /* out param for our server reply */
                           bson_error_t *error)
    {
       /*
        * mongoc_collection_insert_one requires an uninitialized, stack-allocated
        * bson_t to receive the update result
        */
       bson_t local_reply;
       bson_t *doc = NULL;
       ctx_t *data = NULL;
       bool retval;
    
    
       for (int i = 0; i < 1000; i++) {
          doc = BCON_NEW ("new", BCON_INT32 (2), "val", BCON_INT32 (2));
          printf ("Running the user-defined callback in a newly created transaction...\n");
          data = (ctx_t *) ctx;
          retval = mongoc_collection_insert_one (data->collection, doc, data->insert_opts, &local_reply, error);
          {
             sleep(0.5);
          }  
       }
       printf ("sleep end...\n");
       /*
        * To return to the mongoc_client_session_with_transaction() method, set
        * *reply to a new copy of our local_reply before destroying it.
        */
       *reply = bson_copy (&local_reply);
       bson_destroy (&local_reply);
    
       bson_destroy (doc);
       return retval;
    }
    
    mongoc_client_session_with_transaction (session, &create_and_insert_doc, NULL, &ctx, &reply, &error);
    

    当我使用上面的mongoc驱动程序进行Transaction并运行代码时,它仅插入文档就运行了大约5秒。 插入、更新、创建索引等其他操作不会被阻止。为什么?

    我知道mongodb使用意向锁、共享锁、独占锁。因此,如果我进行的事务只插入单个文档,则会为数据库和集合获得一个意向独占锁,为文档获得一个独占锁。

    我想我错过或误解了什么。感谢阅读。

    我运行了测试代码,检查了db.currentOp(),在运行事务时运行了insert、update、create index。

    0 回复  |  直到 1 年前
    推荐文章