设置接口调用超时时间的N种办法
最近遇到调用ldap包接口需要设置接口超时时间,于是略微总结了一下java接口调用设置超时时间的方法:
1.在配置文件application.properties设置
springboot项目:
spring.mvc.async.request-timeout=20000,意思是设置超时时间为20000ms即20s文章来源:https://www.toymoban.com/news/detail-666313.html
2.config配置类中设置
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void configureAsyncSupport(final AsyncSupportConfigurer configurer) {
configurer.setDefaultTimeout(20000);
configurer.registerCallableInterceptors(timeoutInterceptor());
}
@Bean
public TimeoutCallableProcessingInterceptor timeoutInterceptor() {
return new TimeoutCallableProcessingInterceptor();
}
}
3.线程 future.get()中设置(重点)
本次遇到问题并非feign调用,而是本地接口调用,所以没法使用以上两种文章来源地址https://www.toymoban.com/news/detail-666313.html
3.1 线程池的创建
@Configuration
@Slf4j
public 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);
到了这里,关于设置接口调用超时时间的N种办法的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!