gpt4 book ai didi

java - 了解 Playframework 示例项目中的 AsyncController

转载 作者:行者123 更新时间:2023-11-30 06:14:59 27 4
gpt4 key购买 nike

我正在研究 Playframework 概念,我一直坚持使用 AsyncController 示例,该示例说明了以下描述:

This controller contains an action that demonstrates how to write simple asynchronous code in a controller. It uses a timer to asynchronously delay sending a response for 1 second.

我在这里用粗体标记有问题的陈述。

这是 Controller 的代码,我删除了方法的描述,以免浪费问题页面上的空间。

@Singleton
public class AsyncController extends Controller {

private final ActorSystem actorSystem;
private final ExecutionContextExecutor exec;

@Inject
public AsyncControllerSO(ActorSystem actorSystem, ExecutionContextExecutor exec) {
this.actorSystem = actorSystem;
this.exec = exec;
}

public CompletionStage<Result> message() {
return getFutureMessage(1, TimeUnit.SECONDS).thenApplyAsync(Results::ok, exec);
}

private CompletionStage<String> getFutureMessage(long time, TimeUnit timeUnit) {
CompletableFuture<String> future = new CompletableFuture<>();
actorSystem.scheduler().scheduleOnce(
Duration.create(time, timeUnit),
() -> future.complete("Hi!"),
exec
);
return future;
}

}

我不明白为什么 PlayFramework 中给出异步直觉的示例强调“异步延迟定时器”功能?

根据 description of scheduleOnce方法:

Schedules a Runnable to be run once with a delay, i.e. a time period that has to pass before the runnable is executed.

后者是否意味着延迟是在与 message() 方法运行的同一线程中执行的,因此不能将其视为异步?

最佳答案

不讨论 Akka 或 Play 的细节,异步延迟的一般思想是它不会阻塞线程,所以同时可以做其他事情。当您调用 .thenApplyAsync 时,您正在设置一个回调,该回调将在未来的结果准备就绪时执行。因此调度程序知道要做什么:安排在 1 秒内运行 future(如果同时还有其他事情要做,就执行它),一旦 future 准备好,就运行回调。

关于java - 了解 Playframework 示例项目中的 AsyncController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49429252/

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