具有长时间运行任务的spring MVC DeferredResult的示例

时间:2016-03-28 12:00:24

标签: spring spring-mvc spring-async

任何人都可以告诉我,如何使用Spring DeferredResult进行长时间运行的事务任务?经历了网上提供的大量教程,但非基于Rest的应用程序既没有文档也没有示例清楚,它不需要长轮询但在后台运行任务并立即返回HTTP响应和后续调用相同的控制器方法只返回结果。我创建了一些假设,如下所示

private static final Map<String, DeferredResult<ModelAndView>> deferredResults = new ConcurrentHashMap<>();

@RequestMapping(value = "longRunning", method = RequestMethod.POST)
public DeferredResult<ModelAndView> longRunning(@ModelAttribute LongRunningJob longRunningJob) {
    String resultKey = longRunningJob.getKey();                
    DeferredResult<ModelAndView> result = deferredResults.get(resultKey);
    if (result == null ) {
        deferredResults.put(resultKey, result = new DeferredResult<ModelAndView>());
        new Thread(runLongRunning(longRunningJob, result)).start();
    }
    result.onCompletion(() -> {
        deferredResults.remove(resultKey);});
    return result;
}

public Runnable runLongRunning((LongRunningJob newLongRunningJob, DeferredResult deferredResult) {
    return () -> {
        LongRunningJob returnJobValue = this.longRunningJobService.startLongRunningJob(newLongRunningJob); //startLongRunningJob is a transactional method
        ModelMap modelMap = new ModelMap();
        modelMap.put("returnJobValue", returnJobValue);
        modelMap.put("message", "Success");
        deferredResult.setResult(new ModelAndView("job-view", modelMap));
    };
}

它会起作用还是有其他更好的方法来处理它?如果有进入竞争状态的可能性,那么线程安全吗?

0 个答案:

没有答案