加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

java-Spring MVC Async任务同步运行

发布时间:2020-12-15 01:22:46 所属栏目:大数据 来源:网络整理
导读:我想实现一个异步任务,并创建一个页面,该页面可立即返回并在后台启动该任务.但是,页面将等待后台任务完成,然后仅返回.当我访问/ start时,加载页面需要15秒钟的时间.我正在使用Spring 3.2.0.我的一行包含 在我的test-servlet.xml中. 奇怪的是,即使我将@Async

我想实现一个异步任务,并创建一个页面,该页面可立即返回并在后台启动该任务.但是,页面将等待后台任务完成,然后仅返回.当我访问/ start时,加载页面需要15秒钟的时间.我正在使用Spring 3.2.0.我的一行包含< task:annotation-driven />在我的test-servlet.xml中.

奇怪的是,即使我将@Async替换为@Async(“ this_bean_does_not_exist”),应用程序也会执行相同的操作(尽管我期望引用不存在的bean会出现异常).

public interface AsyncTestService {
    void startSlowProcess();
}
@Service
public class AsyncTestServiceImpl implements AsyncTestService {

    @Override
    @Async
    public void startSlowProcess() {
        try {
            Thread.sleep(15000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}
@Controller
public class TestController {

    @Autowired
    AsyncTestService asyncTestService;

    @RequestMapping("/start")
    @ResponseBody
    public String startSlowProcess() {
        asyncTestService.startSlowProcess(); // It takes 15s to complete
        return "STARTED"; // should return immediately
    }
}
最佳答案
您可能需要一个executor.请尝试以下操作:

<task:annotation-driven executor="myExecutor" />    
<task:executor id="myExecutor" pool-size="5"/>

编辑:另一个可能的解决方案:改用EnableAsync(从Spring 3.1开始可用)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读