有两种情况,第一种是业务逻辑复杂,但不需要业务逻辑的结果,第二种是需要返回业务逻辑的处理结果
第一种比较简单,利用多线程处理业务逻辑,或者利用spring中@Asyn注解更简单,
使用@Asyn注解,要首先要配置开启异步注解
@Configuration @EnableAsync public class AsyncConfig { }
然后直接在方法上注解即可
@Service public class AsyncAction { @Async public void fun1() { try { Thread.sleep(10000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("fun1"); } }
第二种需要返回业务逻辑情况则首先需要开启异步支持
public class SpitterWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected void customizeRegistration(Dynamic registration) { registration.setAsyncSupported(true); }或者在web.xml中开启
<servlet> <servlet-name>SpringMvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>...</param-value> </init-param> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet>
然后配置一下线程池
@Configuration @EnableWebMvc @ComponentScan("spittr.web") public class WebConfig extends WebMvcConfigurerAdapter { @Override public void configureAsyncSupport(AsyncSupportConfigurer configurer) { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(5); executor.setMaxPoolSize(10); executor.setQueueCapacity(50); executor.setThreadNamePrefix("abc-"); executor.setKeepAliveSeconds(30); configurer.setTaskExecutor(executor); configurer.setDefaultTimeout(600); }
@Configuration @EnableWebMvc @ComponentScan("spittr.web") public class WebConfig extends WebMvcConfigurerAdapter {
@RequestMapping(value = "/async") public @ResponseBody Callable<String> async() {
return new Callable<String>() { @Override public String call() throws Exception { Thread.sleep(2000); return "Callable result"; } };}