你是對的使用線程池。讓春天爲你照顧它。
假設你使用Spring作爲你的應用程序的選擇,你可以做類似的事情。
您可以爲異步執行程序定義配置類。
@EnableAsync
@Configuration
public class AsyncConfiguration implements AsyncConfigurer {
@Inject
private Environment env;
@Bean
@Override
@Singleton
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(env.getProperty("controller.threadPoolTaskExecutor.corePoolSize", Integer.class, 10));
taskExecutor.setMaxPoolSize(env.getProperty("controller.threadPoolTaskExecutor.maxPoolSize", Integer.class, 100));
taskExecutor.setKeepAliveSeconds(env.getProperty("controller.threadPoolTaskExecutor.keepAliveSeconds", Integer.class, 60*5));
taskExecutor.setQueueCapacity(env.getProperty("controller.threadPoolTaskExecutor.queueCapacity", Integer.class, 10000));
taskExecutor.setThreadNamePrefix("controller-async-task-executor");
return taskExecutor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new AsyncExceptionHandler();
}
}
這裏是你如何定義異常處理程序:
public class AsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(AsyncExceptionHandler.class);
@Override
public void handleUncaughtException(Throwable ex, Method method, Object... params) {
logger.error("Error processing async request in method: " + method.getName(), ex);
}
}
下面是你的控制器看起來是這樣:
@Inject
private AsyncTaskExecutor asyncTaskExecutor;
@GET
@Produces("text/plain")
public void get(@Suspended final AsyncResponse response) throws Exception
{
response.setTimeout(2000, TimeUnit.MILLISECONDS);
asyncTaskExecutor.submit(() -> {
System.out.println("STARTED!!!!");
Thread.sleep(100);
Response jaxrs = Response.ok("hello").type(MediaType.TEXT_PLAIN).build();
response.resume(jaxrs);
});
}