默认的就是连接超时10s,读超时60s
所以可以通过设置Feign.Builder中的options来设置超时时间
来个demo
环境准备,就是一个简单的SpringBoot项目,引入一个Feign的依赖
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
</dependencies>
声明接口 注解
public interface UserApi {
@RequestLine("GET /user/{userId}")
User queryUser(@Param("userId") Integer userId);
}
这里演示的是Feign原生的使用方式,脱离于SpringCloud环境,所以Spring的那些@GetMappring就不支持了,改用Feign本身提供的注解
测试代码
public class FeignDemo {
public static void main(String[] args) {
UserApi client = Feign.builder()
//设置连接和读超时间都是5s
.options(new Request.Options(5, TimeUnit.SECONDS, 5, TimeUnit.SECONDS, true))
.target(UserApi.class, "http://localhost:8088");
User user = client.queryUser(123);
}
}
这里面的请求路径都是不存在的,因为我们只关心传给Client的Options参数值
Client在我们不设置的时候,就用默认的实现Client.Default
断点打到execute方法的实现,运行,走起
结果就是我们设置的5s
2、在接口方法参数设置除了在通过Feign.Builder时设置之外,Feign还支持在接口的方法参数上设置
此时你只需要在接口的方法上加一个Options类型的参数
@RequestLine("GET /user/{userId}")
User queryUser(@Param("userId") Integer userId, Request.Options options);
这样在传参数时就可以设置超时时间了
User user = client.queryUser(123, new Request.Options(3, TimeUnit.SECONDS, 3, TimeUnit.SECONDS, true));
同样地,debug就可以看见我们设置的3s了
这两种设置超时时间的主要区别就是方法参数设置超时时间的优先级高于Feign.Builder设置的超时时间
用一张图来总结一下上面的关系