【发布时间】:2018-02-26 11:39:37
【问题描述】:
我有一个调用三个@Transactional @Async 方法的场景。一切正常,除了所有三种方法都有自己的事务上下文。我想在调用方法的事务上下文中执行它们。
我的调用方法是这样的:
@Transactional
public void execute(BillingRequestDto requestDto) {
try {
LOGGER.info("Start Processing Request : {}", requestDto.getId());
List<Future<?>> futures = new ArrayList<>();
futures.add(inboundProcessingService.execute(requestDto));
futures.add(orderProcessingService.execute(requestDto));
futures.add(waybillProcessingService.execute(requestDto));
futures.stream().parallel().forEach(future -> {
try {
future.get();
} catch (Exception e) {
futures.forEach(future1 -> future1.cancel(true));
throw new FBMException(e);
}
});
requestDto.setStatus(RequestStatus.SUCCESS.name());
requestDto.setCompletedAt(new Date());
LOGGER.info("Done Processing Request : {}", requestDto.getId());
} catch (Exception e) {
requestDto.setStatus(RequestStatus.FAIL.name());
requestDto.setCompletedAt(new Date());
throw new FBMException(e);
}
}
并且所有被调用的方法都用@Async和@Transactional注解。
@Transactional
@Async
public Future<Void> execute(BillingRequestDto requestDto) {
LOGGER.info("Start Waybill Processing {}", requestDto.getId());
long count = waybillRepository.deleteByClientNameAndMonth(requestDto.getClientName(), requestDto.getMonth());
LOGGER.info("Deleted {} Records for Request {} ", count, requestDto.getId());
try (InputStream inputStream = loadCsvAsInputStream(requestDto)) {
startBilling(requestDto, inputStream);
} catch (IOException e) {
LOGGER.error("Error while processing");
throw new FBMException(e);
}
LOGGER.info("Done Waybill Processing {}", requestDto.getId());
return null;
}
这三种方法的实现大致相同。
现在,如果这些方法中的任何一个发生故障,则仅针对该方法回滚事务。
我的要求是在调用方法的事务上下文中运行所有三个方法,这样一个方法中的任何异常都会回滚所有三个方法。
如果我禁用@Async,这种情况会很好。有一些耗时的方法,所以我希望它们并行运行。
请为此提出任何解决方案。
【问题讨论】:
-
@Async方法在单独的线程中执行,因此不能使用调用者的同一个事务。
标签: java spring asynchronous transactions