在 Spring Rest CompletableFuture 结果上使用 @Transactional

Fab*_*ien 5 spring spring-transactions spring-data-jpa spring-web

在我当前的 Web 应用程序中,我对所有服务使用 @RestController 和 CompletableFuture 结果。

数据库操作是异步的(CompletableFuture 方法),但我只想在发送结果之前提交操作

我想在--save--异步结束后提交数据库修改(--save--是未来业务的列表)

@RestController
public class MyController {
...

  @RequestMappping(...)
  public CompletableFuture<ResponseEntity<AnyResource>> service(...){

   CompletableFuture ...
   .thenCompose(--check--)
   .thenAsync(--save--)
   ...ect
   .thenApply(
      return ResponseEntity.ok().body(theResource);
    );
  }

}
Run Code Online (Sandbox Code Playgroud)

-> 我试过@Transactional,但它不起作用(在方法结束时提交但异步方法部分或未执行

-> 程序化的其他方式:

@RequestMappping(...)
public CompletableFuture<ResponseEntity<AnyResource>> service(...){

DefaultTransactionDefinition def = new DefaultTransactionDefinition();
// explicitly setting the transaction name is something that can only be done programmatically
def.setName("SomeTxName");
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

TransactionStatus status = this.platformTransactionManager.getTransaction(def);

CompletableFuture ...
   .thenCompose(--check--)
   .thenAsync(--save--)
   ...ect
   .thenApply(

this.platformTransactionManager.commit(status)

      return ResponseEntity.ok().body(theResource);
    );

}
Run Code Online (Sandbox Code Playgroud)

发生错误“无法停用事务同步 - 未激活”,推测是因为不是同一线程。

有没有正确的方法,将事务性与 CompletableFuture 一起使用?