码迷,mamicode.com
首页 > 编程语言 > 详细

springmvc异步处理请求

时间:2018-07-18 16:59:53      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:return   efi   params   支持   comm   ret   isp   aci   tde   

有两种情况,第一种是业务逻辑复杂,但不需要业务逻辑的结果,第二种是需要返回业务逻辑的处理结果

第一种比较简单,利用多线程处理业务逻辑,或者利用spring中@Asyn注解更简单,

使用@Asyn注解,要首先要配置开启异步注解

  1. @Configuration
  2. @EnableAsync
  3. public class AsyncConfig {
  4. }

然后直接在方法上注解即可

  1. @Service
  2. public class AsyncAction {
  3. @Async
  4. public void fun1() {
  5. try {
  6. Thread.sleep(10000);
  7. } catch (InterruptedException e) {
  8. // TODO Auto-generated catch block
  9. e.printStackTrace();
  10. }
  11. System.out.println("fun1");
  12. }
  13. }


切记异步类的bean不能被重复扫描,而且只能被sping容器的上下文扫描,不能被spingmvc扫描,否则异步失效

第二种需要返回业务逻辑情况则首先需要开启异步支持

  1. public class SpitterWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
  2. @Override
  3. protected void customizeRegistration(Dynamic registration) {
  4. registration.setAsyncSupported(true);
  5. }
或者在web.xml中开启

  1. <servlet>
  2. <servlet-name>SpringMvc</servlet-name>
  3. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  4. <init-param>
  5. <param-name>contextConfigLocation</param-name>
  6. <param-value>...</param-value>
  7. </init-param>
  8. <load-on-startup>1</load-on-startup>
  9. <async-supported>true</async-supported>
  10. </servlet>

然后配置一下线程池

  1. @Configuration
  2. @EnableWebMvc
  3. @ComponentScan("spittr.web")
  4. public class WebConfig extends WebMvcConfigurerAdapter {
  5. @Override
  6. public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
  7. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  8. executor.setCorePoolSize(5);
  9. executor.setMaxPoolSize(10);
  10. executor.setQueueCapacity(50);
  11. executor.setThreadNamePrefix("abc-");
  12. executor.setKeepAliveSeconds(30);
  13. configurer.setTaskExecutor(executor);
  14. configurer.setDefaultTimeout(600);
  15. }
  1. @Configuration
  2. @EnableWebMvc
  3. @ComponentScan("spittr.web")
  4. public class WebConfig extends WebMvcConfigurerAdapter {


这样就可以开始异步处理任务了,能够尽快释放servlet线程,缓解高并发问题

  1. @RequestMapping(value = "/async")
  2. public @ResponseBody Callable<String> async() {
 return new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(2000);
                return "Callable result";
            }
        };
}






            

springmvc异步处理请求

标签:return   efi   params   支持   comm   ret   isp   aci   tde   

原文地址:https://www.cnblogs.com/jpfss/p/9329410.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!