异步 Servlet 到底有什么优势?我曾假设这意味着 Web 应用程序容器侦听器线程将被“释放”以处理另一个客户端请求,同时由 Servlet 执行一个可能长时间运行的任务。Tomcat 和 Spring 3.2 的实验不支持这一点。好处是某种内存管理改进吗?
我已将 Tomcat 设置为侦听单个线程。我@Controller
调用下游@Service
调用Thread.sleep(10000)
. 我每隔一秒发出两个请求,第一个请求需要 10 秒才能得到响应,然后又需要 10 秒才能得到第二个响应(总共需要 20 秒)。如果我对异步 Servlet 的理解是正确的,我希望能在 11 秒内得到两个响应。
弹簧配置:
<mvc:annotation-driven>
<mvc:async-support task-executor="taskExecutor" default-timeout="20000" />
</mvc:annotation-driven>
<context:component-scan base-package="com.company" />
<task:executor id="taskExecutor" pool-size="5-20" queue-capacity="100"/>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:/spring-config/app-context.xml
</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:/spring-config/web-context.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
控制器
@Controller
public class AsyncController {
@Autowired
private BlockingService service;
@RequestMapping("/test")
public @ResponseBody Callable<String> test()
{
return new Callable<String>() {
public String call() throws Exception {
return service.block(System.currentTimeMillis());
}
};
}
}
服务
@Service
public class BlockingService {
public String block(long timeBefore)
{
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Before: "+timeBefore+"\nTime: "+System.currentTimeMillis();
}
}