gpt4 book ai didi

multithreading - Quarkus 应用程序的 @Async 等价物是什么?

转载 作者:行者123 更新时间:2023-12-05 02:03:14 25 4
gpt4 key购买 nike

<分区>

在一个类中,我想调用一个方法,但不必等到方法结束。通常在 spring 应用程序中我会使用 @Async,但在 Quarkus 应用程序中该怎么做?

下面是一个简单的入门示例。在“StartWork”类中,“Work”开始。 (我省略了工作接口(interface),但您可以看到它的一个实现:WorkA)。调用“work.do()”后,startWork() 方法应该继续执行,而无需等待 work.do() 完成。

@ApplicationScoped
public class WorkA implements Work {
public void do() {
System.out.println("Starting work A.");
try {
Thread.sleep(1000l);
System.out.println("Finished work A.");
} catch(InterruptedException ex) {
System.out.println("My work got interrupted.");
}
}
}

@ApplicationScoped
public class StartWork {

@Inject
Work work;

public void startWork() {
work.do();
System.out.println("I dont' care when and if the work finished, but it has started.");
}
}

这是同一个例子,但现在我尝试使用 Mutiny:

@ApplicationScoped
public class WorkA implements Work {
public void do() {
Uni.createFrom().voidItem().invoke(Runnable -> {
System.out.println("Starting work A.");
try {
Thread.sleep(1000l);
System.out.println("Finished work A.");
} catch(InterruptedException ex) {
System.out.println("My work got interrupted.");
}
}
});
}

@ApplicationScoped
public class StartWork {

@Inject
Work work;

public void startWork() {
work.do();
System.out.println("I dont' care when and if the work finished, but it has started.");
}
}

运行此示例时,我没有看到正在打印的行。所以我猜匿名 runnable 没有被调用?

最小可重现产品:https://gitlab.com/rmvanderspek/quarkus-multithreading

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com