avatar

使用 MongoDB Replica Set 來測試 Transaction 功能

說來慚愧,但現在才算第一次正式用上 MongoDB 的 Transaction 功能,在兜弄的過程中也記下了一些自家遇到的問題。對 Transaction 還不清楚的可以參考一下 MongoDB 文件的介紹,一般 transaction 會用到一連串的 IO 行為,而且你希望能確保行為的一致性,也就是說你做了 A、B、C 三個行為,一旦其中的某處發生問題,你希望不會發生「部分資料寫入」的情況發生,這時候 transaction 就派上用場,直到確定所有行為都正常執行完成,才作 commit write。

這功能是從 4.0 之後才加入了,4.2 之後才算穩定

In version 4.0, MongoDB supports multi-document transactions on replica sets.

In version 4.2, MongoDB introduces distributed transactions, which adds support for multi-document transactions on sharded clusters and incorporates the existing support for multi-document transactions on replica sets.

不過遇到本地開發的問題,因為你必須要起一個叢集才能測試,不然你會看到這個錯誤訊息

MongoError: Transaction numbers are only allowed on a replica set member or mongos

這也是本文要解決的問題

簡單的解法可以參考這篇文章 - Introducing run-rs, a Zero Config MongoDB Replica Set Runner,這是該文作者提供的一個方便的工具 - run-rs,能簡單在本地起一個 MongoDB 叢集。不過如果你的開發環境是以 container 為主的話又不行了...0rz

所以後來又找到了 MongoDB® packaged by Bitnami,Bitnami 這名字應該有些開發者會有點印象,所以這專案有本家的精神存在 😎,可以方便起一個 MongoDB 叢集,基本上需要的資訊都在這個段落可以找到。

這邊是簡單的 docker-compose 範例,可以簡單起好需要的環境:

也可以用簡單的方式連進 DB 去看裡面的資料

mongo --host localhost --port 27017 --username pguser --password 12345 dev_staging

以上,收工! 至於各語言怎麼實作,大家就直接參考官方文件吧 😙

powered by WebMention.io

You can tweet this post or discuss it on Twitter, the comments will show up here.
0Likes0Replies0Mentions

Be the first one to share this article!