设置接口调用超时时间的N种办法
最近遇到调用ldap包接口需要设置接口超时时间,于是略微总结了一下java接口调用设置超时时间的方法:
1.在配置文件application.properties设置
springboot项目:
spring.mvc.async.request-timeout=20000,意思是设置超时时间为20000ms即20s
2.config配置类中设置
public class WebMvcConfig extends WebMvcConfigurerAdapter {@Overridepublic void configureAsyncSupport(final AsyncSupportConfigurer configurer) {configurer.setDefaultTimeout(20000);configurer.registerCallableInterceptors(timeoutInterceptor());}@Beanpublic TimeoutCallableProcessingInterceptor timeoutInterceptor() {return new TimeoutCallableProcessingInterceptor();}}
3.线程 future.get()中设置(重点)
本次遇到问题并非feign调用,而是本地接口调用,所以没法使用以上两种
3.1 线程池的创建
@Configuration@Slf4jpublic class CommonThreadPoolConfig { @Bean("asyncExecutor") public ThreadPoolTaskExecutor asyncExecutor(){ ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); //核心线程数-可从配置文件获取方便更改 executor.setCorePoolSize(2); //最大线程数 executor.setMaxPoolSize(Runtime.getRuntime().availableProcessors()); //队列容量 executor.setQueueCapacity(100); //设置非活跃线程的活跃时间(超时无任务则变为非活跃状态) executor.setKeepAliveSeconds(60); //设置线程名字 executor.setThreadNamePrefix("asyncExecutor-"); //设置拒绝策略 executor.setRejectedExecutionHandler( new ThreadPoolExecutor.CallerRunsPolicy()); //设置线程工厂 executor.setThreadFactory(Executors.defaultThreadFactory()); //等待所有任务结束后再关闭线程池 executor.setWaitForTasksToCompleteOnShutdown(true); return executor; }}
3.2 使用线程池
@Resource(name = "asyncExecutor")private ThreadPoolTaskExecutor asyncExecutor;
3.3 调用远程接口
//调用接口Future<Boolean> future = asyncExecutor.submit(()->ldapService.authenticateWithOutCache(authWithOutCacheReqDTO));//设置超时时间future.get(5,TimeUnit.SECONDS);
来源地址:https://blog.csdn.net/m0_37635053/article/details/127606422