Node.js中数据同步的最佳实践 [英] best practice for data synchronization in nodejs
问题描述
我正在尝试在两个系统之间进行一些集成,并且在同步数据时遇到了一些问题.
I'm trying to do some integration between two systems, and I've got some problems when it comes to synchronizing data.
我正在使用 nodejs ,并且数据库是 mongodb 或 firebase .
I am using nodejs and the database is mongodb or firebase.
场景描述如下:
- 具有dbA的systemA
- 带dbB的systemB
执行以下操作:
-
systemA向systemB发送一个请求(POST或PUT),而
body
如下:
{
.....
fieldA1: valueA1,
fieldA2: valueA2
.....
}
然后,systemB需要根据systemA数据更新dbB中的几个字段(fieldB1,fieldB2),如下所示:
then systemB needs to update several fields(fieldB1, fieldB2) in dbB according to the systemA data, like this:
fieldB1: valueA1
fieldB2: valueA2
两者 fieldB1
和 fieldB2
成功更新后,然后执行更多逻辑
after BOTH fieldB1
and fieldB2
are updated successfully, then execute more logic
我正在使用 async
来控制异步过程.我的代码实现了这3个步骤:
I'm using async
to control asynchronous process. My code to implement these 3 steps:
async.waterfall([
function (callback) {
//get valueA1 of fieldA1 and valueA2 of fieldA2
},
async.parallel([
function (callback) {
//set valueA1 to fieldB1
},
function (callback) {
//set valueA2 to fieldB2
}
], function (err, result) {
//more logic here
})
], function (err, result) {
//more logic here
})
由于 fieldB1
和 fieldB2
应该同时更新 ,这两种情况均无法更新 fieldB1
或 fieldB2
将导致数据不一致,这不是正确的结果.
Since fieldB1
and fieldB2
should be updated at the same time, either situation when failing to update fieldB1
or fieldB2
will lead to data inconsistency, which is not the correct result.
但是, async.parallel
不能保证任何更新失败都会回滚或阻止其他人的更新吗?在更新 fieldB1
和 fieldB2
时,有什么方法可以理想地保持 BOTH 的数据一致性吗?
However, async.parallel
cannot guarantee that any update failure will rollback or prevent the others' update right ? Is there any way to idealy keep the data consistency of BOTH when updating fieldB1
and fieldB2
?
推荐答案
我发现很难将您的代码映射到Firebase API.但是您所描述的听起来像是可以通过使用交易来实现的或多位置更新.
I find it difficult to map your code to the Firebase API. But what you're describing sounds like its achievable by either using transactions or multi-location updates.
我过去在以下内容中详细介绍了这些类型的更新:如何在Firebase中写入非规范化数据
I covered these type of updates in-depth in the past in: How to write denormalized data in Firebase
这篇关于Node.js中数据同步的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!