使用Java的CompletableFuture怎么回滚事务?

写了一个示意的代码,主要是通过exceptionally来控制异常信息futureA 是测试类,futureB 和C是并行的线程,加一个CompletableFuture result = CompletableFuture.allOf(futureA,futureB,futureC)保证ABC都处理完了才可以继续调用流程

public static void main(String[] args) throws Exception {

//回滚测试
CompletableFuture<String> futureA = CompletableFuture.supplyAsync(()->{
  System.out.println("启动A");
  try {
    //异步调用
    Thread.sleep(1000);
    Test.pring();
  } catch (InterruptedException e) {
    //异常处理
    e.printStackTrace();
  }
  return "completableFutureA";
  }).exceptionally(throwable -> {
    System.out.println(throwable.getMessage());
    throw new RuntimeException(throwable.getMessage());
  }).thenCombine(CompletableFuture.supplyAsync(() -> {
    throw new RuntimeException("异常报错");
  }).exceptionally(throwable->{
    System.out.println(throwable.getMessage());
    throw new RuntimeException(throwable.getMessage());
  }),(s1,s2)->s1+ " " + s2);
CompletableFuture
<String> futureB = CompletableFuture.supplyAsync(()->{   System.out.println("启动B");   try {     //异步调用     Thread.sleep(100);     Test.pring();   } catch (InterruptedException e) {     //异常处理     e.printStackTrace();   }   return "completableFutureB"; }); CompletableFuture<String> futureC = futureA.thenApplyAsync((c)->{   System.out.println("启动C");   try {     //异步调用     Test.pring();   } catch (Exception e) {     //异常处理     e.printStackTrace();   }   return "completableFutureC"; }); // System.out.println("阻塞读取"); CompletableFuture result = CompletableFuture.allOf(futureA,futureB,futureC); System.out.println("读取结果 :"+ futureA.get() + futureB.get()+futureC.get()); System.out.println(result); }

尝试一下在exceptionally中进行异常报错或者手动回滚,我这里是直接抛出异常,信息如图

image

 

posted @ 2025-10-30 16:21  黄进广寒  阅读(7)  评论(0)    收藏  举报