[英]How to make spring controller json response wait until firebase query ends?
I'm using an ajax call to spring controller to start a firebase query, save the result to local database and return items saved in the local database (including the results saved from the current and previous firebase queries too).我正在使用 ajax 调用 spring controller 来启动 firebase 查询,将结果保存到本地数据库并返回保存在本地数据库中的项目(包括从当前和以前的 firebase 查询保存的结果)。 The problem is that since the firebase query runs async, the results from the local database query are returned before the firebase query finishes.
问题在于,由于 firebase 查询运行异步,本地数据库查询的结果在 firebase 查询完成之前返回。 How can I make the returned local database query wait until the firebase query finished?
如何让返回的本地数据库查询等到 firebase 查询完成?
@PostMapping("/firebase-download")
@ResponseBody
public List<FirebaseTransactionRecord> firebaseDownload() {
firebaseService.downloadAndSaveFirebaseTransactions();
// wait for the query to end
return firebaseTransactionRecordRepository.findBySentFalse();
}
@Override
@Transactional
public void downloadAndSaveFirebaseTransactions() {
final List<FirebaseTransactionRecord> firebaseTransactions = new ArrayList<>();
firebaseDb.child(StringValueConstant.DB_CHILD_TEMPORARY_TRANSACTIONS)
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot userSnapshot : snapshot.getChildren()) {
userSnapshot.getChildren().forEach(transactionSnapshot -> {
FirebaseTransactionRecord record = firebaseTransactionMapper
.toFirebaseTransactionRecord(transactionSnapshot);
firebaseTransactions.add(record);
});
}
saveFirebaseTransactionRecords(firebaseTransactions);
}
@Override
public void onCancelled(DatabaseError error) {
log.error("Error reading Firebase data:", error);
}
});
}
@Override
@Transactional
public void saveFirebaseTransactionRecords(List<FirebaseTransactionRecord> firebaseTransactions) {
firebaseTransactions.forEach(firebaseTransaction -> {
if (!firebaseTransactionRecordRepository.existsByReferralNumber(firebaseTransaction.getReferralNumber())) {
firebaseTransactionRecordRepository.save(firebaseTransaction);
}
});
}
Something with a CountdownLatch
should do the trick.带有
CountdownLatch
的东西应该可以解决问题。
Set the initial latch counter to 1 (for the main listener), then set it to the number of child nodes in onDataChange
.将初始闩锁计数器设置为 1(对于主侦听器),然后将其设置为
onDataChange
中的子节点数。 Next pass the latch to saveFirebaseTransactionRecords
and decrease it when each transaction completes.接下来将闩锁传递给
saveFirebaseTransactionRecords
并在每个事务完成时减少它。 Once the latch reaches 0, you can exit out of downloadAndSaveFirebaseTransactions
一旦闩锁达到 0,您就可以退出
downloadAndSaveFirebaseTransactions
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.