简体   繁体   English

Firebase:在单个事务中更新多个对象

[英]Firebase: Update multiple objects in single transaction

I have found some thread below which talk about this scenario. 我在下面找到了一些讨论这个场景的线程。

However still struggling to find, if there are any recommended data structure design for this. 但是仍然很难找到,如果有任何推荐的数据结构设计。 I see a Multi-write library firebase-multi-write which says you probably don't need this in most cases. 我看到一个多写库firebase-multi-write ,它说你在大多数情况下可能不需要这个。

But I think I do need this, my scenario is : 3 users 但我认为我确实需要这个,我的情况是:3个用户

/users/A : {credit:20}

/users/B : {credit:3}

/users/C :  {credit:10}

And each user can steal credits from each other all at the same time ., 每个用户可以在同一时间窃取对方学分。,

  • A steals from B credits look like {21, 2} B点数的抢断看起来像{21,2}
  • B steals from C credits look like {3, 9} 来自C点数的B抢断看起来像{3,9}
  • C steals from A credits look like {11, 20} 来自A学分的C抢断看起来像{11,20}

Now I need to update the credits for each user to maintain this consistency, so that each steal operation is atomic in nature. 现在我需要为每个用户更新信用以保持这种一致性,这样每个窃取操作本质上都是原子的。

What will be the best way to handle such scenario, while maintaining data integrity in Java ? 在保持Java数据完整性的同时,处理此类场景的最佳方法是什么?

In setember/2015 firebase developers released new version . 2015年9月,firebase开发者发布了新版本

With this release, you can now do this in a single atomic update to both locations: 在此版本中,您现在可以在两个位置的单个原子更新中执行此操作:

Firebase ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
// Generate a new push ID for the new post

Firebase newPostRef = ref.child("posts").push();
String newPostKey = newPostRef.getKey();

// Create the data we want to update
Map newPost = new HashMap();
newPost.put("title", "New Post");
newPost.put("content", "Here is my new post!");

Map updatedUserData = new HashMap();
updatedUserData.put("users/posts/" + newPostKey, true);
updatedUserData.put("posts/" + newPostKey, newPost);

// Do a deep-path update
ref.updateChildren(updatedUserData, new Firebase.CompletionListener() {
   @Override
   public void onComplete(FirebaseError firebaseError, Firebase firebase) {
       if (firebaseError != null) {
           System.out.println("Error updating data: " + firebaseError.getMessage());
       }
   }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM