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

Jos*_*zka 7 spring asynchronous spring-mvc

我想从控制器内部启动异步任务,如下面的Spring docs代码片段.

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()); 

  } 
} 
Run Code Online (Sandbox Code Playgroud)

之后在另一个请求中(在任务运行的情况下)我需要检查任务的进度.Basicaly获得cn的值.

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

谢谢

PepaProcházka

mat*_*sev 16

你看过Spring参考文档中的@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();
    }
}
Run Code Online (Sandbox Code Playgroud)

接下来,从控制器调用它:

@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());
    }        
}
Run Code Online (Sandbox Code Playgroud)

请记住相应地配置执行程序,例如

<task:annotation-driven executor="myExecutor"/>
<task:executor id="myExecutor" pool-size="5"/>
Run Code Online (Sandbox Code Playgroud)

  • 你好,我已经阅读了这篇文档,我会尝试这个或Euguene sollution.感谢大家的帮助.如果你现在如何使用它,春天是如此美好:-) (2认同)