【问题标题】:CompletableFuture to make multiple DB calls and get the response backCompletableFuture 进行多个数据库调用并获取响应
【发布时间】:2021-08-13 05:57:21
【问题描述】:
如何对数据库进行异步调用并保存详细信息并取回响应实体?假设我要访问两个不同的数据中心。如何将实体作为响应返回?
CompletableFuture.supplyAsync(() -> abcDc1Repository.save(localEntity));
CompletableFuture.supplyAsync(() -> abcDc2Repository.save(localEntity));
【问题讨论】:
标签:
java-8
completable-future
【解决方案1】:
您可以使用CompletableFuture.allOf()
CompletableFuture<OrderEntity> firstFuture = CompletableFuture.supplyAsync(
() -> firstRepository.save(firstEntity)
);
CompletableFuture<OrderEntity> secondFuture = CompletableFuture.supplyAsync(
() -> secondRepository.save(secondEntity)
);
CompletableFuture.allOf(firstFuture, secondFuture).join();
OrderEntity firstEntity = firstFuture.get();
OrderEntity secondEntity = secondFuture.get();
如果您保存新实体,则不需要结果。 Hibernate 会将 id 设置为传递的实体。
来自SimpleJpaRepository
@Transactional
@Override
public <S extends T> S save(S entity) {
if (entityInformation.isNew(entity)) {
em.persist(entity);
return entity;
} else {
return em.merge(entity);
}
}
备注
请记住,CompletableFuture.supplyAsync() 使用公共 fork-join 池。因此,您的操作将在应用程序的任何点等待stream.parallel() 操作。
另外,这两个调用不应该有一个公共事务(一个持久化上下文,带有@Transactional),因为持久化上下文不是线程安全的。