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 {

}

posted on   乐之者v  阅读(797)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 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的解决办法
< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

导航

统计

点击右上角即可分享
微信分享提示