当后端对于数据量较大的处理或是某些耗时的操作时,需要先对请求接口的请求进行响应。
- 配置接口,使用Call<V>进行返回
@GetMapping("test")
public Callable<BaseResponse> query() {
return new Callable<BaseResponse>() {
@Override
public BaseResponse call() throws Exception {
BaseResponse response = new BaseResponse(StatusCode.Success);
try {
response.setData("返回消息");
Thread.sleep(10000);
log.info("相应test接口");
} catch (Exception e) {
response = new BaseResponse(StatusCode.Fail.getCode(), e.getMessage());
}
return response;
}
};
}
- 增加配置
在WebMvcConfigurer接口的实现类中进行配置
@Configuration
public class SysWebMvcConfigurer implements WebMvcConfigurer {
@Bean
public ContributorInterceptor contributorInterceptor(){
return new ContributorInterceptor();
}
@Override
public void configureAsyncSupport(final AsyncSupportConfigurer configurer) {
configurer.setDefaultTimeout(5 * 1000L);
configurer.registerCallableInterceptors(timeoutInterceptor());
configurer.setTaskExecutor(threadPoolTaskExecutor());
}
@Bean
public TimeoutCallableProcessingInterceptor timeoutInterceptor() {
return new TimeoutCallableProcessingInterceptor();
}
@Bean("threadPoolTaskExecutor")
public ThreadPoolTaskExecutor threadPoolTaskExecutor(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(4);//设置线程池中线程的个数
executor.setMaxPoolSize(8);//设置线程池中可容纳线程的最大个数
executor.setKeepAliveSeconds(10);//设置线程存活时间
executor.setQueueCapacity(8);//设置等待处理的任务队列
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());//设置超过最大线程数时需要执行的策略(等待策略)
return executor;
}
}
请求接口测试: