Java中对Spring控制器的异步支持

时间:2015-07-01 00:15:50

标签: java spring spring-mvc asynchronous

当我尝试拨打我的春季网络客户端时,我收到错误:

HTTP Status 500 - Request processing failed; nested exception is java.lang.IllegalStateException: Async support must be enabled on a servlet and for all filters involved in async request processing. This is done in Java code using the Servlet API or by adding "true" to servlet and filter declarations in web.xml.

我没有访问/而不是弄乱web.xml文件。我的弹簧控制器如下:

@Controller
@RequestMapping("/test/test")
public class MyController
{
     //Using DeferedResult and Http get / post
}

我尝试的事情:将@Async放在上面的类和上面的get / post方法之上。还尝试将@EnableAsync放在类之上。如何在java代码中启用异步支持而不在web.xml中执行?无法在网上找到太多帮助

1 个答案:

答案 0 :(得分:2)

如果使用java样式的应用程序上下文而不是xml,则下面的配置应该可以正常工作

@Configuration
@EnableAutoConfiguration
@EnableAsync
@ComponentScan("your.package")
public class AppConfig extends SpringBootServletInitializer implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(20);
        executor.setMaxPoolSize(100);
        executor.setQueueCapacity(200);
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new MyAsyncExceptionHandler();
    }
}

此处还有asyncExceptionHandler

的示例
public class MyAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {

    static Logger log = Logger.getLogger(MyAsyncExceptionHandler.class.getName());

    @Override
    public void handleUncaughtException(Throwable throwable, Method method, Object... obj) {
        log.error("Exception message - " + throwable.getMessage());
        log.error("Method name - " + method.getName());
        for (Object param : obj) {
            log.error("Parameter value - " + param);
        }

    }

}