本文介绍了Spring MVC中如何获得运行异步任务的进度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从控制器内启动异步任务像从春天文档以下code sniplet。

I would like to start an asynchronous task from within controller like in following code sniplet from 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()); 

  } 
} 

在事后要求annother(在情况下任务运行时)我需要检查任务的进度。 Basicaly得到CN的价值。

afterwards in annother request (in the case that task is running) I need to check the progress of the task. Basicaly get the value of cn.

什么是最好的形式给出Spring MVC中一个如何避免syncronisation问题。

What would be the best aproach in Spring MVC a how to avoid syncronisation issues.

感谢

佩帕普罗恰兹卡

推荐答案

你有没有看的 @Async 注释href=\"http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/scheduling.html#scheduling-annotation-support-async\">Spring参考文档?

Have you looked at the @Async annotation in the Spring reference doc?

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

First, create a bean for your asynchronous task:

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

接着,从控制器调用它:

Next, call it from the 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中如何获得运行异步任务的进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 15:44