如何处理多次写入,以便如果一次写入失败,则不会提交数据? [英] How to treat multiple writes so that if one write fails, the data isn't committed?
问题描述
在 Firebase实时数据库中,我需要将child_node1
添加到node1
,然后紧接着将child_node2
添加到node2
,该信息是相关的.
In Firebase Realtime Database, let's say that I need to add a child_node1
to node1
and, immediately after that, a child_node2
to node2
, the information being related.
我可以轻松地在插入第一个子节点的完成处理程序中添加第二个子节点.但是,如果用户恰好在第二次通话期间关闭了该应用程序,该怎么办?还是网络突然掉线了?
I could easily add the second child node in the completion handler of the insertion of the first child node. But what if the user closes the app exactly during the second call? Or the network suddenly goes down?
当且仅当两个调用(事务)均成功时,我如何才能确保提交信息?
How should I make sure that the information gets committed if and only if both calls (transactions) succeed?
例如,在主节点(users
)中创建用户后,我还要根据其位置将其添加到另一个名为users-locations
的节点中.如果在添加users
之后但没有完成添加users-locations
之前发生错误怎么办?
For example, after creating a user in the main node (users
), I want to also add him in another node called users-locations
according to his location. What if an error occurs after adding in users
but before finishing adding in users-locations
?
谢谢!
推荐答案
您要尝试的是扇出操作,正如Doug所说,您通常希望通过单个多位置更新来完成此操作.多位置更新的规模比交易要好得多.
What you're trying to do is a fan-out operation, and as Doug commented you'll typically want to do this with a single multi-location update. Multi-location updates scale much better than transactions.
例如,一次写入两个位置:
For example, to write to both locations at once you'd do:
let updates = ["/node1/child_node1": "value", "/node2/child_node2": "value"]
ref.updateChildValues(updates)
一些用于阅读有关这些内容的好资料是:
Some great sources for reading more about these are:
- 博客文章中介绍了多位置更新
- 博客文章讨论使用扇出操作的多位置更新
- 我对采用非规范化数据的数据一致性策略的回答
- Andrew关于相似主题的答案
- 一个提到多位置更新的问题
- the blog post introducing multi-location updates
- the blog post discussing using multi-location updates for fan-out operations
- my answer on strategies for data consistency with denormalized data
- Andrew's answer on a similar topic
- an answer showing how to do multi-location deletes
- many other questions mentioning multi-location updates
这篇关于如何处理多次写入,以便如果一次写入失败,则不会提交数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!