异步处理
在Servlet3.0版本中引入了异步处理的功能,使线程可以返回到容器,从而执行更多的任务
使用AysncContext来进行异步操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| public interface ServletRequest {
public AsyncContext startAsync() throws IllegalStateException; public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) throws IllegalStateException; public boolean isAsyncStarted();
public boolean isAsyncSupported();
public AsyncContext getAsyncContext();
}
public interface AsyncContext { void dispatch();
void dispatch(String path);
void dispatch(ServletContext context, String path); void complete(); void start(Runnable run); void addListener(AsyncListener listener);
void addListener(AsyncListener listener, ServletRequest request, ServletResponse response); }
|
要在servlet上启用异步处理,需要配置asyncSupported为true
以tomcat为例,看一下异步是怎么处理的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| @Override public AsyncContext startAsync() { return startAsync(getRequest(),response.getResponse()); }
@Override public AsyncContext startAsync(ServletRequest request, ServletResponse response) { if (!isAsyncSupported()) { IllegalStateException ise = new IllegalStateException(sm.getString("request.asyncNotSupported")); log.warn(sm.getString("coyoteRequest.noAsync", StringUtils.join(getNonAsyncClassNames())), ise); throw ise; }
if (asyncContext == null) { asyncContext = new AsyncContextImpl(this); }
asyncContext.setStarted(getContext(), request, response, request==getRequest() && response==getResponse().getResponse()); asyncContext.setTimeout(getConnector().getAsyncTimeout());
return asyncContext; }
|