如何优雅的同步等待vertx异步回调AsyncResult

如何优雅的同步等待vertx异步回调

在vertx中,所有的api,均为异步回调。在实际项目开发中,这些异步回调,将导致出现回调地狱的问题。往往我们需要已同步的方式,调用这些异步方法。

为了可以将异步任务编排起来,vertx为我们提供几套参考的方案:

情景

在一个spring技术栈构建的应用A中,需要通过vertx service proxy调用由vertx构建的下游服务。应用A中,我们是需要获取下游服务的异步结果。

通常我们需要一个Future来做这件事情。但vertx的提供Future的不具备阻塞获取结果的能力(The Golden Rule - Don’t Block the Event Loop,这也能理解)。

这里提供一个小demo,减少样板代码。

下游vertx服务
@ProxyGen
public interface HelloService {
    void sayHello(String name, Handler<AsyncResult<String>> resultHandler);
}
@ProxyGen
public interface NameService {
    void getName(Handler<AsyncResult<String>> resultHandler);
}
应用A调用方
@RestController
public class HelloController {

    @Autowired
    private HelloService helloService;

    @Autowired
    private NameService nameService;

    @GetMapping("/index")
    public String index() throws ExecutionException, InterruptedException {
        String name = AwaitUtil.awaitResult(resultHandler -> this.nameService.getName(resultHandler));
        String msg = AwaitUtil.awaitResult(resultHandler -> this.helloService.sayHello(name, resultHandler));
        return msg;
    }

}
AwaitUtil
public class AwaitUtil {

    public static <T> T awaitResult(Consumer<Handler<AsyncResult<T>>> runnable) throws ExecutionException, InterruptedException {
        // TODO: 2022/12/5 如果是在vertx的io线程调用future.get()会导致io线程陷入死阻塞
        checkVertxEventLoop();
        CompletableFuture<T> future = toCompletableFuture(runnable);
        return future.get();
    }

    public static <T> CompletableFuture<T> toCompletableFuture(Consumer<Handler<AsyncResult<T>>> runnable) {
        checkVertxEventLoop();
        CompletableFuture<T> future = new CompletableFuture<>();
        Handler<AsyncResult<T>> resultHandler = newHandler(future);
        runnable.accept(resultHandler);
        return future;
    }

    private static <T> Handler<AsyncResult<T>> newHandler(CompletableFuture<T> future) {
        return event -> {
            if (event.succeeded()) {
                future.complete(event.result());
            } else future.completeExceptionally(event.cause());
        };
    }

    private static void checkVertxEventLoop() {
        if (isInVertxEventLoop()) throw new RuntimeException("not support blocking call in vertx eventLoop");
    }

    private static boolean isInVertxEventLoop() {
        return Thread.currentThread() instanceof VertxThread && ((VertxThread) Thread.currentThread()).isWorker();
    }
}
说明

既可以使用awaitResult()直接获取异步结果,亦可使用toCompletableFuture()得到CompletableFuture在后续需要结果的时候get()

不要在Vertx EventLoop里调用任务阻塞方法,要一个线程中既要执行异步方法,又要阻塞get结果,显然是不可能的,除非是用kotlin协程或者Java协程框架quasar

效果

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值