feign设置超时时间
引入依赖包
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.0.2.RELEASE</version>
</dependency>
feign设置超时时间
feign的 本质是 调用 http请求,如果不设置超时时间,请求长时间连接着,占用系统资源,影响用户体验。
feign设置超时时间,可以通过 Request.Options 来设置。
FeignClientFactoryBean :
调用 feign ,会调用 FeignClientFactoryBean 类的 feign() 方法,再用 configureFeign() 配置 feign 。
protected Feign.Builder feign(FeignContext context) {
FeignLoggerFactory loggerFactory = get(context, FeignLoggerFactory.class);
Logger logger = loggerFactory.create(this.type);
Feign.Builder builder = get(context, Feign.Builder.class)
// required values
.logger(logger)
.encoder(get(context, Encoder.class))
.decoder(get(context, Decoder.class))
.contract(get(context, Contract.class));
//配置 feign。
configureFeign(context, builder);
return builder;
}
在 内部的 configureUsingConfiguration() 可以看到:
// Request.Options 配置的超时时间,会在这里 添加到 feign配置中。
Request.Options options = getOptional(context, Request.Options.class);
if (options != null) {
builder.options(options);
}
代码示例:
- FeignTimeoutConfiguration 配置类:
@Configuration
public class FeignTimeoutConfiguration {
@Value("${feign.connect.time:10000}")
private int connectTimeout;
@Value("${feign.read.time:5000}")
private int readTimeout;
@Bean
public Request.Options options() {
return new Request.Options(connectTimeout, readTimeout);
}
}
- FeignClient 注解 指定配置:
在 configuration 属性中,指定配置为 以上设置的 FeignTimeoutConfiguration 即可。
@FeignClient(name = "myService", configuration = FeignTimeoutConfiguration.class)
@RequestMapping("/myService")
public interface MyFeignService {
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
2022-03-20 PageHelper基础知识
2019-03-20 微服务SpringCloud无法进行服务消费
2018-03-20 HTTP请求出现405状态码method not allowed的解决办法