RestEasy异步控制器正确使用

时间:2016-01-20 23:36:02

标签: java multithreading rest asynchronous resteasy

我正在尝试使用RestEasy创建异步REST服务,但我找不到任何显示干净方法的文档。我发现的唯一例子是:

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();
   }

在方法中创建新线程似乎不是在生产环境中执行操作的最佳方式。我觉得我应该从线程池或其他东西获取一个线程。

任何有关更好示例的建议或链接都​​会非常有用。

1 个答案:

答案 0 :(得分:0)

您使用线程池是正确的。让Spring为你照顾它。

假设您使用Spring作为应用程序的选择,您可以执行类似的操作。

您可以为Async Executors定义一个Configuration类。

@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);
    });
}