广告
返回顶部
首页 > 资讯 > 后端开发 > JAVA >设置接口调用超时时间的N种办法
  • 137
分享到

设置接口调用超时时间的N种办法

javaspring开发语言 2023-09-03 09:09:48 137人浏览 泡泡鱼
摘要

设置接口调用超时时间的N种办法 最近遇到调用ldap包接口需要设置接口超时时间,于是略微总结了一下java接口调用设置超时时间的方法: 1.在配置文件application.properties

设置接口调用超时时间的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

--结束END--

本文标题: 设置接口调用超时时间的N种办法

本文链接: https://www.lsjlt.com/news/391922.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作