原文链接:https://blog.csdn.net/sinat_37356064/article/details/78116116
项目中有个从页面发起的AJAX请求后台需要处理十分钟以上,这导致页面超时卡死,
为了解决这个问题,经讨论,我们采用后台异步处理,用到了spring的@Async,用法很简单。
首先在spring的xml配置文件中添加如下配置:
xmlns:task="http://www.springframework.org/schema/task"
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.0.xsd">
<task:annotation-driven />
其次在需要异步执行的方法上添加@Async注解即可:
package async;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MyController {
@Resource
MyService myService;
@RequestMapping("/testAsync.do")
@ResponseBody
public Map<String, Object> testAsync(HttpServletRequest req){
Map<String, Object> resultMap = new HashMap<String, Object>();
String param = req.getParameter("param");
//调用异步执行的方法
myService.excuteAsync(param);
resultMap.put("resultMsg", "异步处理中...");
return resultMap;
}
}
——————————————分割线——————————
package async;
import org.springframework.scheduling.annotation.Async;
public class MyService {
//需要异步处理的业务方法
@Async
public void excuteAsync(String param){
// do something;
}
}
页面超时的问题解决了,但是异步方法什么时候执行完,
操作人员如果想知道进度或第一时间知道执行结果怎么办呢?
目前想到了三种解决方法:
一、异步方法执行完后,发送邮件给操作人;
二、实时查询后台执行的进度显示在页面;
三、异步方法执行完后,再在页面给一个提示。
我们采用的是第一种,至于每一种的具体实现,这里就不详述了。
流程图