gpt4 book ai didi

Spring MVC如何获得运行异步任务的进度

转载 作者:行者123 更新时间:2023-12-04 09:54:15 24 4
gpt4 key购买 nike

我想从 Controller 内部启动一个异步任务,如Spring文档中的以下代码片段所示。

import org.springframework.core.task.TaskExecutor; 

public class TaskExecutorExample {

private class MessagePrinterTask implements Runnable {

private int cn;

public MessagePrinterTask() {

}

public void run() {
//dummy code
for (int i = 0; i < 10; i++) {
cn = i;
}
}

}

private TaskExecutor taskExecutor;

public TaskExecutorExample(TaskExecutor taskExecutor) {
this.taskExecutor = taskExecutor;
}

public void printMessages() {

taskExecutor.execute(new MessagePrinterTask());

}
}

之后在另一个请求中(如果任务正在运行),我需要检查任务的进度。基本上得到cn的值。

Spring MVC中最好的方法是如何避免同步问题。

谢谢

佩帕·普罗查兹卡(PepaProcházka)

最佳答案

您是否看过Spring reference doc中的@Async批注?

首先,为您的异步任务创建一个bean:

@Service
public class AsyncServiceBean implements ServiceBean {

private AtomicInteger cn;

@Async
public void doSomething() {
// triggers the async task, which updates the cn status accordingly
}

public Integer getCn() {
return cn.get();
}
}

接下来,从 Controller 调用它:
@Controller
public class YourController {

private final ServiceBean bean;

@Autowired
YourController(ServiceBean bean) {
this.bean = bean;
}

@RequestMapping(value = "/trigger")
void triggerAsyncJob() {
bean.doSomething();
}

@RequestMapping(value = "/status")
@ResponseBody
Map<String, Integer> fetchStatus() {
return Collections.singletonMap("cn", bean.getCn());
}
}

请记住相应地给执行者 configure签名,例如
<task:annotation-driven executor="myExecutor"/>
<task:executor id="myExecutor" pool-size="5"/>

关于Spring MVC如何获得运行异步任务的进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10899635/

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