springmvc异步处理请求

时间:2022-10-15 13:45:36

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

第一种比较简单,利用多线程处理业务逻辑,或者利用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");
	}
}


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

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

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 {


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

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