调用后退出该方法,但方法应继续处理 JAVA 中提交的请求



>问题陈述 -我开发了一个Web应用程序,该应用程序根据用户输入创建一组任务并在远程执行这些任务 服务器 (Linux( 按顺序逐个排列。每个任务大约需要 10 分钟才能完成。通常用户在一个请求中提交 5 个任务,这意味着 Web 应用程序大约需要 50 分钟才能在用户屏幕上显示成功/失败消息 任务提交。我不希望用户为了显示输出结果而等待 50 分钟,而是想在消息页面上呈现并期望该方法应该继续处理传递的数据。

当前实现- 控制器将从用户那里获取准备任务所需的所有数据并传递给将创建任务列表的服务类 - 列出并开始 通过调用执行任务方法按如下方式执行它们。一旦执行完成的任务,那么到目前为止,只有我可以向用户显示最终的成功/失败消息。但是我 想要在调用 executeTask(( 后通过传递 taskList 并期望以下结果退出 -

1( executeTask(( 方法即使在退出方法后也应继续处理提交的数据。

2(我将向用户呈现成功页面并显示消息 - 您的请求已成功提交。任务执行完成后,您将收到通知消息。

public List<String> executeTask(List<Task> taskList){
List<String> executionStatusList = new ArrayList<String>();
Process process = null;
for( Task task : taskList) {
try {
process = Runtime.getRuntime().exec(task );
if (process.waitFor() == 0) {
int exitVal = process.exitValue();
executionStatusList.add("SUCCESS");
} else {
executionStatusList.add("ERROR");
break; //Since error occured while processing the task , exiting without processing other task with error status.
}
} catch (IOException ioException) {
//LOGS
} catch (InterruptedException intrruptdExcptn) {
//LOGS
} finally {
if (null != process) {
process.destroy();
executionStatusList.add("SUCCESS");
} else {
executionStatusList.add("ERROR");
break; //Since error occured while processing the task , exiting without processing other task with error status.
}
}

}
return executionStatusList;
}

为什么不创建一个异步运行的新线程并向客户端发送回 200 ok 响应?使用它来表示请求已记录,您将通过电子邮件收到一封邮件。还是我错过了什么?

我使用了 spring 支持的异步功能来实现给定的要求。我们需要在需要时间处理的方法上添加异步功能。通过这样做,该特定方法将继续在后台运行,我们可以填充向用户提交消息。

代码示例

@EnableAsync
public class ServiceClassName {
/**
*Method which takes long time to process request. Here Need to add @Asyncn
*/
@Async("asyncExecutor")
public void methodName ( DataaType inputParam) {
//Your business logic goes here
//If you want to return something, then do link  as below-
//return CompletableFuture.completedFuture(returnValue);
}
}

最新更新