调用我的后端服务时,我的前端超时(504 错误)。这是因为我的后端服务大约需要 6 分钟才能完成运行。我想在一分钟内向前端返回响应,并在将响应提供给前端后让我的后端代码继续运行。
我想使用并发来运行两个代码段。一个线程将向前端返回一个字符串,另一个线程将调用在我的服务器上运行大约 5 分钟的代码。
我希望我的解决方案简单,因为这似乎是一个需要解决的简单问题,因此我使用 java.util.concurrent 中的简单 Executor 类
我的 Invoker 类如下:
public class Invoker implements Executor {
@Override
public void execute(Runnable r) {
r.run();
}
}
在我的实际代码中,我有
import java.util.concurrent.Executor;
import com.dcc.standalone.Invoker;
public String aCoolFunction() {
String status = "good job, homie";
Executor executor = new Invoker();
executor.execute( () -> {
// Call this part of the code that takes 5 minutes to run CODE_A
});
return status;
}
我希望在 CODE_A 开始运行的同时返回状态。相反,代码像以前一样按顺序运行,即在 CODE_A 运行后返回状态。
最佳答案
也许使用CompletableFuture
?
设置 ThreadPoolTaskExecutor。
@Configuration
@EnableAsync
public class SpringAsyncConfig {
@Bean(name = "threadPoolTaskExecutor")
public Executor threadPoolTaskExecutor() {
return new ThreadPoolTaskExecutor();
}
}
定义你的函数
public String aCoolFunction() {
String status = "good job, homie";
someAsyncFunction();
return status;
}
定义异步长时间运行函数。
@Async
public void someAsyncFcuntion() {
// Call this part of the code that takes 5 minutes to run CODE_A
}
在CompletableFuture
中的某个地方运行你的酷函数
String result CompletableFuture.supplyAsync(() -> aCoolFunction()).get();
我是通过手机写作的,但这是我从脑海中想到的。
关于java - 如何同时运行两个代码段: one returns a String the other returns void,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57367115/