3

谁能告诉我,如何使用 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));
    };
}

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

4

0 回答 0