【发布时间】:2021-07-03 17:16:54
【问题描述】:
我是 CompletableFuture 的新手,我想要做的是我在 Spring Boot 项目中有这个逻辑,我正在尝试使用 CompletableFuture 将其转换为并行处理方法。
@Transaction
void serviceMethod{
for(Object obj : objList) //objlist can have 10000 objects and its a multi level composite objects
{
//Get corresponding entity obj from the database, if not found throw user exception
//Process i.e. change some fields
}
}
在上述逻辑中,该方法使用 @Transaction 注释,我没有显式调用 JPA save 来保存实体。
现在,我正在尝试使用上述逻辑进行并行处理。
@Transaction
void serviceMethod{
for(Object obj : objList) //objlist can have 10000 objects and its a multi level composite objects
{
//Get corresponding entity obj from the database, if not found throw user exception
CompletableFuture<Optional<Obj>> optionalObjFuture = CompletableFuture.supplyAsync( () -> {//get the object from repository})
CompletableFuture<Obj> objFuture = optionalObjFuture.thenApply( optionalObj -> {
if(obj.isPresent()){
return obj.get();
}
else{
throw user exception;
}
})
////Process i.e. change some fields
}
}
现在的问题是
- 当出现异常时,我必须遵循什么方法来中断 for 循环?
- 在这种情况下如何处理事务。有没有什么方法可以处理事务而不需要对存储在数据结构中的已处理对象调用 saveAll?
【问题讨论】:
标签: exception spring-transactions spring-boot-actuator completable-future