java - 如何同时运行两个代码段: one returns a String the other returns void

标签 java spring spring-boot concurrency

调用我的后端服务时,我的前端超时(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

设置 ThreadPoolTask​​Executor。

@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/

相关文章:

java - 将元素添加到 Canvas JavaFX

spring - 在没有 Spring Security 的情况下,DelegatingFilterProxy 在 Spring MVC 应用程序上调用了两次

java - 如何保护@ConfigurationProperties 类免受更改?

java - 如何在公共(public)pom中保留版本号并在其他pom文件中使用它(spring maven项目)

java - 使用 thymeleaf 将整数中的分值转换为 HTML 中的货币

java - 将值从映射转换为集合

java - Runtime.exec 没有运行但没有异常

java - 调用 RedisOperationsSessionRepository.delete 时出现 NoSuchMethodError

java - Spring Actuator/health 对 JSON 的 XML 响应

spring-boot - 如何解决h2数据库和spring boot中错误的用户名和密码错误?