我有一个请求处理程序,它在内部进行一些繁重的操作并且需要大约5秒才能返回。该请求返回一个包含3个集合的Model。最重的集合需要大约2秒来处理,它们都是独立的。我想尝试在请求中并行运行它们,但我尝试过的任何东西似乎都没有用。我所看到的是tomcat处理前几个请求,但很快它就会窒息而停止。
这是Iv尝试过的:
我有一个实用程序,它使用Callable,在一个非常大的Executor上运行它们,然后返回FutureTasks。
public class Async {
public static boolean active = true;
private static ExecutorService exe = active ? Executors.newFixedThreadPool(50) : null;
public static FutureTask run(Callable callable) throws Exception {
FutureTask f = new FutureTask(callable);
if (active) {
exe.execute(f);
} else {
f.run();
}
return f;
}
}
我这样使用它:
@RequestMapping("/test")
public
@ResponseBody
MessageDto authenticate(HttpServletRequest request, HttpServletResponse response) throws Exception {
final Map<String, Object> responseMap = new HashMap<String, Object>();
FutureTask future1 = Async.run(new Callable() {
@Override
public Object call() throws Exception {
try {
[SOME PROCESS THAT TAKES ABOUT 2 SECS]
} catch (Exception ex) {
LOG.error(ex);
}
return null; //To change body of implemented methods use File | Settings | File Templates.
}
});
FutureTask future2 = Async.run(new Callable() {
@Override
public Object call() throws Exception {
try {
[SOME PROCESS THAT TAKES ABOUT 2 SECS]
} catch (Exception ex) {
LOG.error(ex);
}
return null; //To change body of implemented methods use File | Settings | File Templates.
}
});
FutureTask future3 = Async.run(new Callable() {
@Override
public Object call() throws Exception {
try {
[SOME PROCESS THAT TAKES ABOUT 1 SEC]
} catch (Exception ex) {
LOG.error(ex);
}
return null; //To change body of implemented methods use File | Settings | File Templates.
}
});
future1.get();
future2.get();
future3.get();
return new MessageDto(responseMap);
}
我也试过使用Spring的@Async,但结果相同,服务器卡住了。 请帮忙 感谢