2016-01-20 78 views
1

我想使用RestEasy創建一個異步REST服務,但我找不到任何文檔顯示這樣做的乾淨方式。我發現的唯一的例子是在這裏:RestEasy異步控制器正確使用

https://github.com/resteasy/Resteasy/blob/master/jaxrs/async-http-servlet-3.0/async-http-servlet-3.0-test/src/main/java/org/jboss/resteasy/test/async/JaxrsResource.java

@GET 
    @Produces("text/plain") 
    public void get(@Suspended final AsyncResponse response) throws Exception 
    { 
     response.setTimeout(2000, TimeUnit.MILLISECONDS); 
     Thread t = new Thread() 
     { 
     @Override 
     public void run() 
     { 
      try 
      { 
       System.out.println("STARTED!!!!"); 
       Thread.sleep(100); 
       Response jaxrs = Response.ok("hello").type(MediaType.TEXT_PLAIN).build(); 
       response.resume(jaxrs); 
      } 
      catch (Exception e) 
      { 
       e.printStackTrace(); 
      } 
     } 
     }; 
     t.start(); 
    } 

創建的方法一個新的線程似乎並不喜歡做的事情在生產環境中的最佳途徑。我覺得我應該從線程池或其他東西獲得線程。

任何建議或鏈接到更好的例子將是非常有益的。

回答

0

你是對的使用線程池。讓春天爲你照顧它。

假設你使用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); 
    }); 
}