使用Spring的WebAsyncTask异步请求时出错Can't set AsyncWebRequest with concurrent handling in progress

使用Spring的WebAsyncTask异步请求时出现如下错误:

java.lang.IllegalStateException: Cannot forward after response has been committed
java.lang.IllegalStateException: Can't set AsyncWebRequest with concurrent handling in progress
org.springframework.web.util.NestedServletException: Request processing failed; 
Caused by: java.lang.IllegalStateException: Can't set AsyncWebRequest with concurrent handling in progress
    at org.springframework.util.Assert.state(Assert.java:392)
    at org.springframework.web.context.request.async.WebAsyncManager.setAsyncWebRequest(WebAsyncManager.java:108)

表面上看错误描述并不清楚。这里我仅仅记录我的解决方法,我这里是因为时间超时引起的。也许你也是这样的情况:
原代码结结构如下:

@RequestMapping(value = { "/webAsyncTask/test" })
    public WebAsyncTask test(HttpServletRequest request) {
        Callable<String> callable = new Callable<String>() {
            public String call() throws InterruptedException {
                String string = new String();
                Thread.sleep(15000);
                return string;
            }
        };
        return new WebAsyncTask(callable);
    }

这里直接返回的new WebAsyncTask(callable)报错。我是通过设置超时时间解决的:返回new WebAsyncTask(60000, callable);
注意:即使设置里超时时间而没做超时处理,这样是不严谨的。因为当60000毫秒之后call()没执行完依然会报异常。Spring对超时处理提供有WebAsyncTask.onTimeout()方法。
所有我最终的代码结构如下:

@RequestMapping(value = { "/webAsyncTask/test" })
    public WebAsyncTask test(HttpServletRequest request) {
        Callable<String> callable = new Callable<String>() {
            public String call() throws InterruptedException {
                String string = new String();
                Thread.sleep(15000);
                return string;
            }
        };
        WebAsyncTask asyncTask = new WebAsyncTask(60000, callable);
        asyncTask.onTimeout(new Callable<String>() {
            public String call() throws Exception {
                String string = "请求超时!";
                return string;
            }
        });
        return asyncTask;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值